I have tried to program a random number generator that doesn't generate the same random number more than once. But I am unable to and can't figure out why. My code is like this at the moment:
public void printNS(){
System.out.print("Numeros Numeros: ");
for(int i=0; i < 5 ; i++){
System.out.print( (int)(Math.random()*50) + ",");
}
System.out.print("; Numeros Stars: ");
for(int i=0; i < 2 ; i++){
System.out.print( (int)(Math.random()*12)+ ",");
}
}
in java 8 you can do the following
int[] rand = new Random().ints(start, end).distinct().limit(number).toArray();
for more details/options see the doc
And before java 8 you can use a Set. Generate the random numbers until your set size is less than the desired number of random numbers
So you want k distinct random numbers from 0 to n (with k < n).
Two possible approaches:
Pick k random numbers, as you already did, and store them in a data structure. Everytime you pick a number, check if it is already contained in the structure: if it is, keep picking until you have a "new" random number. It is a simple enough approach but the loop could potentially block your application. I suggest to use a Set since it stores distinct elements by definition
Set<Integer> set = new LinkedHashSet<>(); // unordered
while (set.size() < k){
set.add((int)(Math.random()*n));
}
System.out.println(set);
Create a List and initialize it with every number between 0 and n. Then shuffle it. First k elements of the list are the numbers you want.
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++){
list.add(i);
}
Collections.shuffle(list);
list.subList(0, k).clear();
System.out.println(list);
I would suggest the second approach as it is more clean, I don't know your efficiency requirements though.
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