Random element generation without duplicates Java [duplicate]

天大地大妈咪最大 提交于 2019-12-14 03:32:29

问题


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]);
        }


    }

}

回答1:


There are many different approaches you can consider, depending on how flexible the algorithm should be.

Taking 5 random elements from a list of 6, is the same as selection 1 element from the list of 6 that you don't choose. This is a very inflexible, but very easy.

Another approach could be to delete the element from the list, and decrease the maximum random number. In this cause I would advice to not use a String[].




回答2:


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.




回答3:


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:


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).




回答5:


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




回答6:


If I understand you correctly, then you want to choose n-1 elements at random from a list of n elements. If yes, then I recommend to choose just one at random and take all the others.

Arrays.shuffle(fruit);
int notThis = numberGenerator.nextInt(6);
for(int i = 0; i < fruit.length; i++)
    if(i!=notThis) System.out.println(fruit[i]);



回答7:


Copy your array into List<String>, then shuffle it, then just pick elements one by one:

List<String> copy = new ArrayList<>(Arrays.asList(fruit));
Collections.shuffle(copy);
for (String f : copy)
    System.out.println(f);



回答8:


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);
        }
      }

}



回答9:


fruit.remove(fruit[nextRandom]);

Maybe, is it the remove sub-method?



来源:https://stackoverflow.com/questions/35227369/random-element-generation-without-duplicates-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!