Random element generation without duplicates Java

2019-09-22 06:29发布

This question already has an answer here:

I am trying to get this code to run without duplicates but am having no success researching this area.

Its the start of a question I am doing which will ask the user to input the missing element. However, when I generate random elements I am getting duplicates

import java.util.Random;

public class QuestionOneA2 {

    public static void main(String[] args) {

        String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();

        for (int i = 0; i < 5; i++) {
            int nextRandom = numberGenerator.nextInt(6);
            System.out.println(fruit[nextRandom]);
        }


    }

}

9条回答
家丑人穷心不美
2楼-- · 2019-09-22 06:54

You can wrap int into 'Interger' and add it to Set. Set holds no duplicates so there will be only unique values in it. So then just check if a Set already has given Integer with Set.contains(Integer).

查看更多
孤傲高冷的网名
3楼-- · 2019-09-22 06:56

You can use a Set to validate if the random generated number is duplicate or not. You just have to keep generating randomNumber until you find a unique random and then add it to the Set to prevent the duplicates.

Here is a quick code snippet:

public static void main(String[] args) {
    String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();
        /* Generate A Random Number */
        int nextRandom = numberGenerator.nextInt(6);
        Set<Integer> validate = new HashSet<>();
        /* Add First Randomly Genrated Number To Set */
        validate.add(nextRandom);
        for (int i = 0; i < 5; i++) {
            /* Generate Randoms Till You Find A Unique Random Number */
            while(validate.contains(nextRandom)) {
                nextRandom = numberGenerator.nextInt(6);
            }
            /* Add Newly Found Random Number To Validate */
            validate.add(nextRandom);
            System.out.println(fruit[nextRandom]);
        }
}

Output:

mango
apple
strawberry
pear
orange
查看更多
贪生不怕死
4楼-- · 2019-09-22 06:57

my personal solution :

private static int[] randomIndexes(int len) {
    int[] indexes = new int[len];
    for (int i = 0; i < len; i++) {
        indexes[i] = i;
    }
    for (int i = len - 1, j, t; i > 0; i--) {
        j = RANDOM.nextInt(i);
        t = indexes[j];
        indexes[j] = indexes[i];
        indexes[i] = t;
    }
    return indexes;
}

See it in action : https://gist.github.com/GautierLevert/a6881cff798e5f53b3fb

查看更多
Anthone
5楼-- · 2019-09-22 06:57

I think it will be easier using an ArrayList, and also controlling the generation of the random number as shown below.

import java.util.Random;

public class QuestionOneA2 {

      public static void main(String[] args) {

        List<String> fruits = new ArrayList<>();

        fruits.add("orange");
        fruits.add("apple");
        fruits.add("pear");
        fruits.add("bannana");
        fruits.add("strawberry");
        fruits.add("mango");

        Random numberGenerator = new Random();
        int nextRandom;

       for (int i = 0; i < 6 ; i++) {
           nextRandom = numberGenerator.nextInt(6 - i);
           System.out.println(fruits.get(nextRandom));
           fruits.remove(nextRandom);
        }
      }

}
查看更多
我想做一个坏孩纸
6楼-- · 2019-09-22 07:02
fruit.remove(fruit[nextRandom]);

Maybe, is it the remove sub-method?

查看更多
时光不老,我们不散
7楼-- · 2019-09-22 07:03

When you generate a random number, I suggest adding it into an array.

Then, when you generate your next number, do some sort of search (google for something efficient) to check if that number is already in the array and thus, has been used already.

If it is, generate a new one, if its not, use it.

You can do this by nesting it in a while loop.

Although, from what I can tell from your question, you would be better off just creating a copy of your fruit array using an ArrayList and then, when you generate a random number to select a fruit, simply remove this fruit from this new list and decrement the range of random numbers you are generating.

查看更多
登录 后发表回答