My goal is to move the elements in the ar[] array into the sorted[] array and sort them from least to greatest. I'm having trouble with that part though because my loop is supposed to find the smallest element in the array and then replace the element with a large number. I think I have most of the code down but when I run the program, every element in the sorted[] array is 2. What am I doing wrong here?
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
ar[i] = 1000000;
}
// print sorted array:
for (int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
What about something like this?
Short and sweet:
import java.util.Arrays;
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = ar.clone();
Arrays.sort(sorted);
System.out.println("Original array: " + Arrays.toString(ar));
System.out.println("Sorted array: " + Arrays.toString(sorted));
}
}
Output:
Original array: [7, 5, 2, 8, 4, 9, 6]
Sorted array: [2, 4, 5, 6, 7, 8, 9]
I don't have my pc now but I think the problem is that once you set the variable smallest with 2 the first time, it remains 2 forever and there is no other number smaller. So I think you are executing the internal if just once and the value is always 2.
Edit. I think that moving the smallest inizialization below the fist for should work.
You didn't do any action when this condition is not true.
if (ar[n] < smallest)
So just smallest element can pass this check and goes on new array.
Also you can sort your array in better shape like this
List<Integer> ar = Arrays.as list ( *your numbers here*);
Collections.sort(ar):
oops, there is a problem inside your loop,
which copy the smallest in ar[] into sorted[], which is 2,
so you are getting 2 in every element inside sorted[].
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n]; <----YOU ALWAYS GET 2 HERE
smallestindex = n;
}
}
sorted[i] = smallest; <---- AND SET 2 TO YOUR sorted[] HERE
ar[i] = 1000000;
}
I don't know if you want a solution or solve it yourself since your question is asking what's wrong, but here it is
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
ar[n] = 1000000; <----CHANGE THE SMALLEST ITEM HERE RATHER THAN OUTSIDE
}
}
sorted[i] = smallest;
}
btw, to make a sorted copy in a easier way:
Firsy make a copy:
int[] sorted = ar.clone();
Then, sort it using Java Util:
Arrays.sort(sorted);
Just 2 lines you get what you want.
I just can't understand, why do we require this, like sorting into another array. You can sort within the array using Arrays.sort() method, or if you want to sort in a different array, you can take following steps:
Copy the array to new array.
Sort the new array and then sort.
If you still want to go with your implementation, then I have refactored your code. Now your code works fine and looks like:
public class Prog1 {
public static void main(String[] args) {
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i = 0; i < ar.length; i++) {
for (int n = 0; n < ar.length; n++) {
if (ar[n] < smallest) {
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
//Your mistake was here.
ar[smallestindex] = 1000000;
smallest=ar[0];
smallestindex=0;
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Your mistake was that you were not reassigning 'smallest' variable. As it was pointing to the smallest element of array so it doesn't get updated in next run because no element in array is less than this variable. Hope you get it. If any questions, you still have, please ask.
Because each time you crush old value (big value) and you don't save it for shifting
smallest = ar[n]; smallestindex = n; You need to add another variable to change values between cells ,or use arraylist for easy way.
int ar[] = {7, 5, 2, 8, 4, 9, 6};
int sorted[] = new int[ar.length];
int smallest = ar[0];
for (int i = 0; i < ar.length ; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) {
smallest = ar[j]; //save small value
ar[j] = ar[i];//transaction between two comparables cells
ar[i] = smallest;//set small value as first
}
sorted[i]=ar[i]; //set first small value
}
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
It seems you want to sort by using an algorithm called 'Selection Sort', but your code is a poorly implement.
You can learn from this brother's question and check the answers below that:
Selection Sort Example
Related
For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections
I know the title is really bad but I spent like 10 minutes thinking of a way to describe my problem in a concise way and couldn't.
This program is supposed to create a numUnique() static method that returns the amount of unique numbers in an array. So, for example, if I have an array with {2, 4, 2, 7, 16, 4} the amount of unique numbers would be 4 (2, 4, 7 and 16).
I was writing the code to find the duplicates in my array, then I realized that I didn't know what to do with it when I had the duplicates, and I've been breaking my head trying to think of a solution but I can't.
Here is the code so far:
public class Unique {
public static void main(String[] args) {
int[] numbers = {1, 6, 2, 14, 6, 8, 2, 1, 23};
numUnique(numbers);
}
public static void numUnique(int[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
//code here
}
}
}
}
My understanding is you to count (not return them all) the number of unique elements in the array. You are attempting to look all the way down, but it's enough to track the number of duplicates as you go. This code looks back to see if the current entry duplicates the previuos one (which works because you sorted, which was a good step).
import java.util.Arrays;
public class Unique {
public static void main(String[] args) {
int[] numbers = {
1,
6,
2,
14,
6,
8,
2,
1,
23
};
System.out.println(numUnique(numbers));
}
public static int numUnique(int[] array) {
Arrays.sort(array);
int dups = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
dups++;
}
}
return (array.length - dups);
}
}
If you want to keep the code that you have so far and sort the list, there are two options that seem to make sense. Where one is to return the number of unique integers, and the other is to return a list of the unique integers.
Returning the number of unique numbers:
public static int numUnique(int[] array) {
ArrayList<Integer> uniques = new ArrayList<>();
Arrays.sort(array);
uniques.add(array[0]);
int prev = array[0];
for (int i = 1; i < array.length; i++) {
if(array[i] != prev){
uniques.add(array[i]);
prev = array[i]
}
}
return uniques.size();
}
Returning the list of unique numbers, would simply require you to return the uniques list, without the .size().
If you want a array instead of a list, you will need to return the following:
return uniques.toArray(new Integer[list.size()]);
If you're using Arrays why not explore it further
private static long numUnique(int[] numbers) {
return Arrays.stream(numbers).distinct().count();
}
Keeping your code as it is:
If You want to know how many non-duplicates are in you array:
public static void numUnique(int[] array) {
Arrays.sort(array);
// Here, make a variable that keeps size of an array
int arrayLenght = array.length;
// Here is our counter:
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
// when you find duplicate, add 1 to our counter:
duplicates++;
}
}
//at the end you can count how many non-duplicates are in the array:
arrayLenght -= duplicates;
System.out.println("There are " + arrayLenght + " non duplicates in our array.");
}
Edit
This solution do not work in every situation.
I know this is not the most optimal way to do this, but the only i know hah:
public static void numUnique(int[] array) {
Arrays.sort(array);
int arrayLenght = array.length;
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
//a little change in our second for-loop:
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j]) {
//Here i'm just summing up the duplicates
duplicates ++;
}
}
// Aaand here, on a console, i print the value (array[i]) and how many duplicates does it have.
//to be exact, if the duplcicates rise only once so it's equal to 1, it means that there is no duplicate of this value (it found itself in the loop).
if (duplicates == 1) {
duplicates = 0;
}
System.out.println(array[i] + " have " + duplicates + "duplicates");
// And what is imporatnt We have to reset our duplication-container!
// so in further loops it will count duplicates for each value in array
duplicates = 0;
}
}
If you find another issue, ask me right away
I'm almost new at Java! I want to control if there are 4 consecutive elements in an array with 5 elements. Is there any way to do that? Can someone help me with that? Thanks! Consecutive like {2, 3, 4, 5}. If there is {3, 4, 2, 5} for example this is not consecutive.I want just a simple example if someone can help me.
I did this but I think this is incorrect:
public int katerTeNjepasnjeshme()
{
int[] numrat=new int[zar.length];
for(int i=0;i<zar.length;i++)
numrat[i]=zar[i].getValue();
int shuma=0;
for(int i=0;i<zar.length-1;i++)
{
if(zar[i+1].getValue()==(zar[i].getValue()+1))
Joptionpane.showMessageDialog(null,"Tere are cons elements");
}
Here's the general idea:
Keep a counter (initialized appropriately), to keep track of the number of consecutive elements as you iterate over the elements.
If the counter reaches 4, you have found 4 consecutive elements.
If you encounter an element that is not consecutive, then reset the counter to 1, and proceed to check the next element.
Here is a sample code snippet:
public static void findConsecutive()
{
int[] array = {1,2,3,5,6,7,8,10};
int counter = 1;
int i = 1;
for (i = 1; i < array.length; i++)
{
if (array[i] == (array[i-1] + 1))
{
counter++;
if (counter == 4)
{
System.out.println("Consecutive elements are at array index: " + (i - 3) + " to " + i);
break;
}
}
else
{
counter = 1;
}
}
}
i think something like that should work:
int[] mylist = new int[10];
for (int i = 0; i < myList.length; i++) {
int k = 1;
for (int j = 1; j < 5 j++) {
if (mylist[i] == mylist[i+j]-j) {
k++;
}
if (k=5) System.out.println("found");
}
}
As soon as you need to compare two elements of the array you should use proper bounds in the loop, otherwise you will get ArrayIndexOutOfBoundsException
boolean consequtive = true;
for (int i = 0; i < zar.length - 1; i++)
if (zar[i+1].getValue() != zar[i].getValue() + 1) {
consecutive = false;
break;
}
if (consequtive)
Joptionpane.showMessageDialog(null,"Tere are cons elements");
Following is the problem-
Given an array of integers as input, return an array that contains the same numbers as that in the input array, but rearranged so that all the even numbers are in front and the odds numbers are at the back. Note that the order of the even numbers and odd numbers should be maintained i.e. if an even number n1 that appears before an even number n2 in the input, then in the output array n1 should appear before n2. The same is true for odd numbers. Also note that in this problem you should not create any new array.
What is done so far is as follows but I am unable to get the expected output.
public class MoveEvenToFront {
static int[] testcase1 = {3, 5, 4, 6, 8, 9, 7, 10};
public static void main(String[] args) {
MoveEvenToFront testInstance = new MoveEvenToFront();
int[] result = testInstance.moveEvenToFront(testcase1);
System.out.print("{");
for (int i = 0; i < result.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(result[i]);
}
System.out.print("}");
}
public int[] moveEvenToFront(int[] arr) {
int temp = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] % 2 != 0) {
temp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = temp;
}
}
return arr;
}
}
The expected output for testcase {1,2,3,4,5,6,7,8,10,12} is {2,4,6,8,10,12,1,3,5,7}.
Your algorithm is wrong. You are checking if arr[i-1] is not even and swapping it with arr[i]. If arr[i] is also odd, then you are not checking for it, and it moves to the front even when it is odd.
What you could do is
find the first even number in the array and swap it with first index and increment the index.
then find the second even number and swap it with second index, continue until end of array.
change the method as shown below:
public int[] moveEvenToFront(int[] arr){
int temp=0;
int a=0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2==0){
for (int j=i;j>a;j--){
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
a++;
}
}
return arr;
}
Try it straight forward:
public static Integer[] NUMBERS = {3,5,4,6,8,9,7,10};
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<>(Arrays.asList(NUMBERS));
int nextIdx = 0;
for (int idx = 0; idx < ints.size(); idx++) {
if (ints.get(idx) % 2 == 0) ints.add(nextIdx++, ints.remove(idx));
}
System.out.println(ints);
}
OUTPUT:
[4, 6, 8, 10, 3, 5, 9, 7]
public void moveEvenToFront(){
int temp=0;
for(int i=0;i<values.length;i++){
for(int j=i;j<values.length;j++){
if(values[j]%2==0){
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
after creating values[], the key point of solving this is identifying where there is an even number and switching with values[0]. and increase by 1 so that the even numbers don't disappear. Hope this helps.
I am trying to create a method which returns an int - the value of the largest integer in the sent array.
The way I want this method to work, is to check the first and the last element of the array in a for-loop, and work their way to the middle. So i = first integer, k = last integer. When i = 0, k = n-1 (indexes), when i = 1, k = n-2 if you catch my drift. In every loop it needs to check if a[i]>a[k]. Then they switch places. Then I know that the largest number is in the leading half of the array, and then I want it to check that half, so ultimately the largest int is at index 0.
I tried like this:
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length/2; i++)
{
k--;
if(a[i]<a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length /=2;
}
return a[0];
}
..but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
EDIT
Also: The array {6,15,2,5,8,14,10,16,11,17,13,7,1,18,3,4,9,12}; will spit out 17 as the largest number. I realize I have to fix the odd-length bug, but I would like to solve this even-length array first..
A bug is when encountering length is odd.
In these cases, you "miss" the middle element.
Example: for input int[] arr = { 8, 1, 5, 4, 9, 4, 3, 7, 2 }; - the element 9 will be compared and checked against itself, but then you reduce the size of length, you exclude 9 from the array you are going to iterate next.
I believe it can be solved by reducing the problem to ceil(length/2) instead of length/2 (and handling special case of length==1)
The other issue as was mentioned in comments is: you need to iterate up to length/2 rather then up to length, otherwise you are overriding yourself.
Lastly - the sign is wrong.
if(a[i]>a[k])
should be
if(a[i]<a[k])
Remember - you are trying to swap the elements if the first is smaller the the second in order to push the larger elements to the head of your array.
but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
In that case you should use a debugger to step through the code to get a picture of what each line of code does.
What I would do is:
public static int maxOfArray(int[] a) {
int max = a[0];
for (int i : a)
if (max < i)
max = i;
return max;
}
public static int findMaxTheHardWay(int[] array) {
for (int length = array.length; length > 1; length = (length + 1) / 2) {
for (int i = 0; i < length / 2; i++) {
if (array[i] < array[length - i - 1])
array[i] = array[length - i - 1]; // don't need to swap.
}
}
return array[0];
}
public static void main(String... args) {
Random rand = new Random(1);
for (int i = 1; i <= 1000; i++) {
int[] a = new int[i];
for (int j = 0; j < i; j++) a[j] = rand.nextInt();
int max = maxOfArray(a);
int max2 = findMaxTheHardWay(a);
if (max != max2)
throw new AssertionError(i + ": " + max + " != " + max2);
}
}
This is rather a crazy way to solve the problem, but I'll play along.
The problem is in the inner loop.
You start out with i = 0 and k = length - 1.
If a[i] > a[k] you swap them.
...
You end up with k = 0 and i = length - 1
If a[i] > a[k] you swap them.
If you look at that carefully you will notice that if we swapped the elements in the first swap, we will also swap them in the last swap; i.e. we will UNDO the effects of the first swap. And the same applies pair-wise through the entire array slice.
See?
What you need to do is to stop the inner loop half way ... and then take account of the case where length is odd.
By the way, the reason I called this "rather crazy", because the obvious and simple way is much faster: O(N) versus O(NlogN)
int a[] = {1,7,3};
List<Integer> list = Arrays.asList(a);
Integer largest = Collections.max(list);
This will give you Largest number in Array.
Here is a solution that fits the specifications that you want (unlike many other here, humm, humm):
final Integer[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
int half = (input.length / 2);
int mod = input.length % 2;
while (half >= 0) {
for (int i = 0, j = (half * 2) + mod - 1; i <= half && j >= half; i++, j--) {
if (input[i] < input[j]) {
final int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}
if (half == 0) break;
half = half / 2;
mod = half % 2;
}
//Here, input[0] = the biggest number in the original input.
Edit: Added mod, so it works if the last element is the largest..
I think your code is working, you just have to ceil the length / 2 in case of odd array but my tests return proper result:
package org.devince.largestinteger;
import java.util.NoSuchElementException;
public class LargestInteger {
final static int[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
// final static int[] input = { 8, 1, 5, 4, 9, 4, 3, 7, 2 };
// final static int[] input = {1,3,7};
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(String.valueOf(maxOfArray(input)));
}
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
k--;
if(a[i]>a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length = (int) Math.ceil(length / 2f);
}
return a[0];
}
}
Why not just store the first value of the array to a variable max.
After that just loop through the array starting from second position till the last ,
in the loop just check if the current value is greater than max or not.If it is greater just assign max that value.
Return max and you have the largest number.
public int FindLargest()
{
int[] num = { 1, 2, 5, 12, 13, 56, 16, 4 };
int max = num[0];
for (int i = 1; i <num.length; i++)
{
if (num[i] > max)
{
max = num[i];
}
}
return max;
}
As the same u can approach like also,
int length = a.length;
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
for(int y = k-1; y >= i; y--)
{
if(a[i]<a[y])
{
int j = a[i];
a[i] = a[y];
a[y] = j;
}
}
}
length /=2;
}
final int validSampleRates[] = new int[]{
5644800, 2822400, 352800, 192000, 176400, 96000,
88200, 50400, 50000, 4800,47250, 44100, 44056, 37800, 32000, 22050, 16000, 11025, 4800, 8000};
ArrayList <Integer> YourArray = new ArrayList <Integer> ():
for (int smaple : validSampleRates){
YourArray.add(smaple);
}
Integer largest = Collections.max(YourArray);
System.out.println("Largest " + String.valueOf(largest));
The best way is to use Array that extends List Collection as ArrayList