简体   繁体   中英

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.

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. 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 has various methods to add, remove clear, size, etc to enhance the usage of this interface

Know and read more about Sets here .

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

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.

That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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