简体   繁体   English

如何生成一个没有重复的随机数数组(在Java中)?

[英]How to generate an array of random numbers without any duplicates (in Java)?

Below is my attempt to populate an array with randomly generated numbers without producing any duplicates. 下面是我尝试用随机生成的数字填充数组而不产生任何重复的尝试。 Yet, I am still getting duplicates. 但是,我仍然在重复。 Where am I going wrong? 我要去哪里错了?

Random rnd = new Random();
int x = 6;
int[] selectionsIndex = new int[x];
String[] pool = {"Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina"}; // = 9

for(int i = 0; i < selectionsIndex.length; i++){
    // Initial random
    selectionsIndex[i] = rnd.nextInt(pool.length);

    // Check whether generated number matches any previously generated numbers
    for(int j = 0; j < i; j++){
        // Match, so generate a new number and restart check
        if(selectionsIndex[i] == selectionsIndex[j]){
            selectionsIndex[i] = rnd.nextInt(pool.length);
            j = 0;
        }
    }
}

You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates. 您可以使用Java中的Set来添加已生成的随机数,这将为您提供数字,并且没有数字会重复。

In code it may look something like this: 在代码中,它可能看起来像这样:

Random rand = new Random();
Set<Integer> uniques = new HashSet<>();
while (uniques.size()<10){
    uniques.add(rand.nextInt(11));
}
for (Integer i : uniques){
    System.out.print(i+" ");
}

Some more information about Sets: 有关集合的更多信息:

  • Set is an interface which extends Collection. Set是扩展Collection的接口。 It is an unordered collection of objects in which duplicate values cannot be stored. 它是对象的无序集合,无法在其中存储重复值。

  • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation). 基本上,Set是由HashSet,LinkedHashSet或TreeSet(排序表示)实现的。

  • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface Set具有多种方法来添加,删除净空,尺寸等,以增强此界面的使用

Know and read more about Sets here . 在此处了解和了解有关Set的更多信息

Here is an alternate solution as well if you are not familiar with sets. 如果您不熟悉集合,这也是一种替代解决方案。

I just made a method to check if the number is already existing in the array. 我只是做了一个方法来检查数组中是否已经存在该数字。 if it is it will get a new number until it is unique. 如果是,它将获得一个新的数字,直到它唯一为止。

        Random rnd = new Random();
        int x = 6;
        int[] selectionsIndex = new int[x];
        String[] pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
        int counter = 0;
        while(counter!=6) {
            int n = rnd.nextInt(pool.length);
            if(!isDuplicate(n,selectionsIndex)) {
                selectionsIndex[counter] = n;
                counter++;
            }
        }

//      testing outputs
//      for(int i = 0; i < selectionsIndex.length ; i++) {
//          System.out.println(selectionsIndex[i]);
//      }

        }
    public static Boolean isDuplicate(int n, int[] a) {
        if(a.length == 0 || a == null) {
            return false;
        }
        for(int i = 0; i < a.length ; i++) {
            if(a[i] == n) {
                return true;
            }
        }
        return false;
    }

The problem is in this part of the code 问题出在代码的这一部分

if(selectionsIndex[i] == selectionsIndex[j]){
            selectionsIndex[i] = rnd.nextInt(pool.length);
            j = 0;
        }

At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this 乍一看,您的代码看起来绝对不错,但细节在于魔鬼,这是简短的答案,只需执行此操作

j =-1 instead of j=0 j =-1而不是j=0

and it'll work fine 而且会很好的工作

The Devil 恶魔

You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all. 您会看到, for循环首先递增,然后在初始化步骤之外继续执行,因此,当您执行j=0您希望检查从0开始,但是它从1开始,因为j递增了,因此未检查0th索引完全没有

That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices. 这就是为什么您只看到0th索引和其他一些索引的重复,而不看到任何其他对索引的重复的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM