Random number generator without replacement?

有些话、适合烂在心里 提交于 2020-01-15 01:06:29

问题


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:

  1. 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);
    
  2. 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.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!