问题
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)+ ",");
}
}
回答1:
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
回答2:
So you want k distinct random numbers from 0 to n (with k < n).
Two possible approaches:
Pick
krandom 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 aSetsince it stores distinct elements by definitionSet<Integer> set = new LinkedHashSet<>(); // unordered while (set.size() < k){ set.add((int)(Math.random()*n)); } System.out.println(set);Create a
Listand initialize it with every number between0andn. Then shuffle it. Firstkelements 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.
回答3:
Here:
private printStars(int loops, int factor) {
for(int i=0; i < loops ; i++){
System.out.print( (int)(Math.random()*factor) + ",");
}
And now:
public void printNS(){
System.out.print("Numeros Numeros: ");
printStars(5, 50);
System.out.print("; Numeros Stars: ");
printStars(2, 12);
Hope that helps. The key point is: when you have repeating code, look at those elements that are "identical"; and then move them into another method!
来源:https://stackoverflow.com/questions/43261147/random-number-generator-without-replacement