Answer the question
In order to leave comments, you need to log in
How to create two lists with unique numbers?
Hello!
I need to do: Create 2 lists of 10 elements from 1 to 100. Check with what attempt you can create lists with unique values. how to implement it correctly?
What am I doing:
List<Integer> list1;
List<Integer> list2;
public void createList(){
int chance = 0;
while (!Collections.disjoint(list1, list2)){
List<Integer> list1 = Collections.nCopies(10, rand.nextInt(100));
List<Integer> list2 = Collections.nCopies(10, rand.nextInt(100));
chance++;
}
list1.forEach(System.out::println);
list2.forEach(System.out::println);
System.out.println(chance);
}
Answer the question
In order to leave comments, you need to log in
You almost did everything right except that Collections.nCopies(10, rand.nextInt(100)); just picks one random number, and makes a list of 10 repetitions of that number. Wangyu that you immediately get lists of different elements on the first try (for example, [17,17,17,17,17,17,17,17,17,17] and [73,73,73,73, 73,73,73,73,73]).
It is necessary to fill the list in a loop, each time calling nextInt(100). Or use the Stream API and write something like
IntStream.range(0, 10).map(i -> rand.nextInt(100)).collect(Collectors.toList());
1. Make a list of 100 items (1, 2, 3...100).
2. Choose randomly from this list, deleting the selected items.
Get it right the first time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question