Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a unique random number for each array value

Tags:

java

random

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];
}
like image 463
N.Cre Avatar asked Sep 06 '15 12:09

N.Cre


1 Answers

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();
like image 114
Tunaki Avatar answered Nov 15 '22 08:11

Tunaki