i want to generate 255 unique random numbers within this range (0-255). so that the array will not contain duplicate records
short [] array =new short[255];
Random rand = new Random();
boolean flag=false;
for (int i=0;i<array.length;i++){
int random_integer = rand.nextInt(255-0) + 0;
for (int j=0;j<i;j++){
if ((short)random_integer==array[j]){
flag=true;
}
}
if (flag==false){
array[i]=(short)random_integer;
}
}
for (int i=0;i<array.length;i++){
System.out.println(array[i]);
}
but i get only first 20 0r 30 items with values and the rest of the array items equals zero.
Solution 1:
I read Jon Skeet's comment, of course, this is the easiest solution:
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 255; i++) {
list.add(i);
}
//and here is the point. Java already have this implemented for you
Collections.shuffle(list);
Or in Java 8 declarative style:
List<Integer> list= IntStream.range(0, 255)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);
or
List<Integer> list = new ArrayList<>();
IntStream.range(0, 255).forEach(list::add);
Collections.shuffle(list);
Solution 2 (picking up on your solution):
You need to generate number for each cell, and check if this number already exists:
short [] array =new short[255];
Random rand = new Random();
for (int i=0; i<array.length; i++) {
int random_integer = -1;
//generate integer while it exists in the array
while(exists(random_integer, array)) {
random_integer = rand.nextInt(255);
}
array[i] = random_integer;
}
And now, let's check whether it exists:
public boolean exists(int number, int[] array) {
if (number == -1)
return true;
for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}
Of course, you can use a hashmap for example, to speed up the exists()
method, i.e. to lower the complexity from O(n) to O(1);
If you can use java 8:
List<Integer> randIntegers = new Random().ints(1, 256).distinct().limit(255).boxed().collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With