I got this simple code and I want to simplify the comparsion with array in while loop
int[] numbers = new int[7];
Random rand = new Random();
for(int i = 0; i < 7; i++) {
int number = rand.nextInt(46);
while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||
number == numbers[4] || number == numbers[5] || number == numbers[6]) {
number = rand.nextInt();
}
numbers[i] = number;
}
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
I want to find a way to simplify this part:
while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||
number == numbers[4] || number == numbers[5] || number == numbers[6])
How can I do that?
A simple solution to this would be to use Java 8 streams.
With streams it looks like this:
int[] numbers = new Random().ints(1, 46).distinct().limit(6).toArray();
Thanks Elliot, I failed to recognice that the number 0
would not be choosen as all ints are 0 at the beginning.
You could use a IntStream
to test if any number from numbers
doesn't match, and only increment when it does. Something like,
for (int i = 0; i < 7;) {
final int number = rand.nextInt(46);
if (IntStream.of(numbers).anyMatch(x -> x != number)) {
numbers[i] = number;
i++;
}
}
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