0

So I want to insert random integers to a list. However, I want to make sure that there are no duplicates on the list. Here is what I have done so far:

while (options.size() <=4) {
    int i = 0;
    int random = ThreadLocalRandom.current().nextInt(answer - 8 ,answer + 8);
    if (random != answer && random != options.get(i-1)) {
        options.add(random);
        i++;
    }
}
1
  • 4
    Use a Set instead. Commented Dec 2, 2021 at 5:53

3 Answers 3

1

The easiest way is with a distinct random stream:

ThreadLocalRandom.current()
        .ints(answer - 8, answer + 8)
        .distinct()
        .limit(5)
        .forEach(options::add);

For better performance on bigger datasets, you can shuffle instead:

List<Integer> range = IntStream.range(answer - 8, answer + 8)
        .boxed()
        .collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
options.addAll(range.subList(0, 5));
Sign up to request clarification or add additional context in comments.

Comments

1

Since you want distinct values in your collection, use a LinkedHashSet and add values in it.

Set<Integer> options = new LinkedHashSet<>();
while (options.size() <= 4) {
    int i = 0;
    int random = ThreadLocalRandom.current().nextInt(answer-8, answer+8);
    if (random != answer) {
        options.add(random);
        i++;
    }
}

Once done, you can convert the set to a list (if required for further processing)

List<Integer> list = set.stream().collect(Collectors.toList());

Comments

-1

It turns out all I needed was the contain function

while (options.size() <=4){
        int i = 0;
        int random = ThreadLocalRandom.current().nextInt(answer -8 ,answer +8 );
        if (random != answer && !options.contains(random)){
            options.add(random);
            i++;
        }

    }

2 Comments

contains on a List is O(n) - that makes this algorithm a hugely inefficient O(n^2). Use a LinkedHashSet instead.
Is there a reason why you don't use java.util.Set?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.