Ecco un modo alternativo che utilizza un set e lo riempie fino a raggiungere le dimensioni richieste. Genera numeri ToDraw numeri casuali distinti nell'intervallo da min a max (incluso). Conserva anche l'ordine in cui sono stati estratti i numeri (questo è ciò che è LinkedHashSet).
private static Set<Integer> drawNumbers(int min, int max, int numbersToDraw) {
if (max < min) {
throw new IllegalArgumentException("Minimum must be less than maximum.");
}
if (max < 0 || min < 0) {
throw new IllegalArgumentException("Both range numbers must be positive.");
}
final int countOfNumbers = max - min + 1;
if (countOfNumbers < numbersToDraw) {
throw new IllegalArgumentException("Range is not big enough.");
}
final Random randomizer = new SecureRandom();
final Set<Integer> numbersDrawn = new LinkedHashSet<>();
while (numbersDrawn.size() < numbersToDraw) {
final int randomNumber = min + randomizer.nextInt(countOfNumbers);
numbersDrawn.add(randomNumber);
}
return numbersDrawn;
}
Se non si richiedono i numeri per essere unico, è possibile utilizzare questo in Java 8:
final Random randomizer = new SecureRandom();
final List<Integer> numbersDrawn = IntStream
.range(0, numbersToDraw)
.mapToObj(i -> min + randomizer.nextInt(max - min + 1))
.collect(Collectors.toList());
Se non si richiedono i numeri per essere unico, ma si desidera stampare i loro valori distinti (è che la tua domanda originale?):
final Random randomizer = new SecureRandom();
final Set<Integer> numbersDrawn = IntStream
.range(0, numbersToDraw)
.mapToObj(i -> min + randomizer.nextInt(max - min + 1))
.collect(Collectors.toSet());
E un'altra alternativa per il vostro caso concreto:
final Set<Integer> distinctNumbers = Arrays
.stream(lotteryNumbers)
.distinct() // you can leave this as the set is distinct automatically
.boxed()
.collect(Collectors.toSet());
Non si dovrebbe usare casuale. –
Duplicato di http: // StackOverflow.it/questions/8115722/generation-unique-random-numbers-in-java – Satya
@nikpon cosa c'è di sbagliato in 'Random'? È perfettamente soddisfacente – Dici