In Java 8:
final int[] ints = new Random().ints(1, 50).distinct().limit(6).toArray();
In Java 7:
public static void main(final String[] args) throws Exception {
final Random random = new Random();
final Set<Integer> intSet = new HashSet<>();
while (intSet.size() < 6) {
intSet.add(random.nextInt(49) + 1);
}
final int[] ints = new int[intSet.size()];
final Iterator<Integer> iter = intSet.iterator();
for (int i = 0; iter.hasNext(); ++i) {
ints[i] = iter.next();
}
System.out.println(Arrays.toString(ints));
}
Just a little messier. Not helped by the fact that it's pretty tedious to unbox the Set<Integer>
into an int[]
.
It should be noted that this solution should be fine of the number of required values is significantly smaller than the range. As 1..49
is quite a lot larger than 6
you're fine. Otherwise performance rapidly degrades.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…