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 07:06

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]);
查看更多
Bombasti
3楼-- · 2019-09-22 07:10

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[].

查看更多
我只想做你的唯一
4楼-- · 2019-09-22 07:11

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);
查看更多
登录 后发表回答