I have this method that generates a number (1-10) for each array value listed in this method. I want the whole set of numbers to be displayed as a set of unique numbers. How to do this?
public static int generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(10);
lotteryNumbers[1] = randNum.nextInt(10);
lotteryNumbers[2] = randNum.nextInt(10);
lotteryNumbers[3] = randNum.nextInt(10);
lotteryNumbers[4] = randNum.nextInt(10);
return lotteryNumbers[4];
}
An easy solution is to generate a list of the 10 digits, shuffle that list and get the first five elements:
List<Integer> list = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
list.add(i);
}
Collections.shuffle(list);
Integer[] lotteryNumbers = list.subList(0, 5).toArray(new Integer[10]);
Collections.shuffle(list)
is an utility method that randomly permutes the given list in place.
If you are using Java 8, this can be written as:
List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
Collections.shuffle(list);
int[] loterryNumbers = list.subList(0, 5).stream().mapToInt(i -> i).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With