Schming Schming - 10 days ago 5
Java Question

Random number generator giving inconsistent results

I am trying to work out how to add 6 randomly generated numbers to a HashSet. I am getting results but they are inconsistent. Sometimes it prints 6 numbers to the console and other times it prints 5 numbers to the console.

I'm new to this stuff only this morning so I apologize if it is blatantly obvious and thank you for your help.

HashSet<Integer> generatedLotteryNumbers = new HashSet<Integer>();
Random r = new Random();

for(int i=0; i<6; i++){
generatedLotteryNumbers.add(r.nextInt(49));
}

System.out.println(generatedLotteryNumbers);

Answer

A Set cannot contain duplicate values, so if the generator produces the same number twice, it will be removed. Instead, you should loop based on the size of the Set (or use a List):

while (generatedLotteryNumbers.size() < 6) {
    generatedLotteryNumbers.add(r.nextInt(49));
}

If you're using Java 8, another option is to use Random#ints to generate a Stream which you can use to directly create your Set.

Set<Integer> generatedLotteryNumbers = r.ints(0, 49)
                                        .distinct()
                                        .limit(6)
                                        .boxed()
                                        .collect(Collectors.toSet());