Reputation: 101
Now I want to do the sorting part... What is sort? And I so confused about sorting and I need to remove the duplicate numbers... And how to do remove numbers and sort for this coding? p/s:The duplicate numbers I only got a few...
import java.lang.*;
// import java.util.Random;
class UniqueRandomIntArray {
// static Random rnGen = new Random();
private static void uriArray(int[] rray) {
int low = 0;
int high = 100;
int rn;
int haveit = -1;
int i = 0;
int j;
while((haveit == -1) && i < rray.length) {
rn = randNum(low, high);
for(j = 0; j <= i; j++) {
if(rn == rray[j]) {
haveit = j;
j = i;
}
}
if(haveit != -1) {
System.out.println("a[" + haveit + "] is " + rn + " already");
haveit = -1;
}
else {
System.out.println("a[" + i + "] is " + rn);
rray[i] = rn;
i++;
}
} // end while
} // end uriArray
private static int randNum(int min, int max) {
int range = (max - min) + 1;
// int randnum = rnGen.nextInt(range) + min;
int randnum = (int) (Math.random() * range) + min;
return randnum;
}
public static void main(String[] args) {
int[] arra = new int[20];
uriArray(arra);
for(int i=0; i<arra.length; i++) {
System.out.print(" | " + arra[i]);
}
System.out.println(" | ");
}
} //class ends
Upvotes: 0
Views: 523
Reputation: 4922
Replace below code with your current main method and run the program.
for ascending order result use this
Arrays.sort(result);
for descending order result use both
Arrays.sort(result);
Arrays.sort(result, Collections.reverseOrder());
public static void main(String[] args) {
int[] arra = new int[20];
uriArray(arra);
Integer[] result = new Integer[arra.length];
for (int i = 0; i < arra.length; i++) {
result[i] = Integer.valueOf(arra[i]);
}
Arrays.sort(result);
Arrays.sort(result, Collections.reverseOrder()); //comment this line if you want only ascending order results. if you want descending order result keep this line alive
for(int i=0; i<result.length; i++) {
System.out.print(" | " + result[i]);
}
System.out.println(" | ");
}
Let me know if this works for you
Include these packages
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Upvotes: 0
Reputation: 2164
Here is an easy way to generate a unique, random list of ints:
new Random().ints(0, 101)// generate a stream of random integers from 0 (incl.) to 100
.distinct() // unique
.limit(20) // we only need 20 random numbers
.sorted() // sort
.forEach(System.out::println);
So if you want the same result as in your old code, this is your complete new code:
class UniqueRandomIntArray {
public static void main(String[] args) {
new Random().ints(0, 101).distinct() // generate a stream of random
// integers
.limit(20) // we only need 20 random numbers
.sorted().forEach((int i) -> System.out.print(" | " + i));
System.out.println(" | ");
}
} // class ends
Upvotes: 2