不重复随机数生成器?

4
我尝试编写一个“不会生成重复随机数”的随机数生成器,但我无法做到并且也无法找出原因。目前我的代码如下:

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

}

你可以使用一个集合结构体吗? - SedJ601
4
生成真正随机数比你想象中的要困难得多...大多数都是伪随机数。 https://www.random.org/ - brad
一个简单的解决方案是存储您生成的数字,以便稍后检查是否存在重复。但这会带来内存成本。 - Junbang Huang
1
你能否更清楚地阐述你想要问什么? - qre0ct
当然,我想要实现的是,例如我的输出是:数字数字:29,29,8,38,4; 数字星:7,8我不希望数字像29一样重复。 - Miguel Ferreira
2
你也可以尝试使用 Collections. Shuffle(0-9 数组)。 - vijayraj34
3个回答

8

在Java 8中,您可以执行以下操作:

 int[] rand = new Random().ints(start, end).distinct().limit(number).toArray();

更多细节/选项,请参见文档

在Java 8之前,您可以使用Set。生成随机数,直到您的Set大小小于所需的随机数数量。


2

您想从 0n 中选择 k 个不同的随机数(其中 k < n),涉及到IT技术相关内容。

有两种可能的方法:

  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);
    
我建议采用第二种方法,因为它更加简洁。不过我不知道你的效率要求是什么。

好的,谢谢你,再问一下,有没有更简单的方法来随机生成数字,就像我做的那样,但更简单? - Miguel Ferreira
你是什么意思?Math.random() 对我来说看起来很简单 - Oneiros

0

这里:

private printStars(int loops, int factor) {
  for(int i=0; i < loops ; i++){
    System.out.print( (int)(Math.random()*factor) + ",");
  }

现在:

public void printNS(){
  System.out.print("Numeros Numeros: ");
  printStars(5, 50);
  System.out.print("; Numeros Stars: ");
  printStars(2, 12);

希望有所帮助。关键点是:当您有重复的代码时,请查看那些“相同”的元素,然后将它们移动到另一个方法中!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接