随机数发生器无需更换?

时间:2017-04-06 16:42:28

标签: java random

我试图编写一个随机数生成器不会多次生成相同的随机数。但我无法也无法弄清楚原因。我的代码目前是这样的:

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)+ ",");    
    }

}

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分: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.

答案 2 :(得分:0)

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!