這是一個使用一套並填充它,直到它增長到所需的大小的替代方法。它生成numbersToDraw不同的隨機數字,範圍從分鐘到max(含)。它還保留了繪製數字的順序(這就是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;
}
如果您不需要號碼是唯一的,你可以在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());
如果您不需要號碼是唯一的,但你要打印其獨特的價值(是你原來的問題?):
final Random randomizer = new SecureRandom();
final Set<Integer> numbersDrawn = IntStream
.range(0, numbersToDraw)
.mapToObj(i -> min + randomizer.nextInt(max - min + 1))
.collect(Collectors.toSet());
併爲您的具體情況多了一個選擇:
final Set<Integer> distinctNumbers = Arrays
.stream(lotteryNumbers)
.distinct() // you can leave this as the set is distinct automatically
.boxed()
.collect(Collectors.toSet());
你不應該使用隨機。 – 2015-09-06 12:22:00
重複http:// stackoverflow。com/questions/8115722/generated-unique-random-numbers-in-java – Satya
@nikpon「隨機」有什麼問題?這非常好 – Dici