Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify comparsion with array

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?

like image 773
1950 Avatar asked Dec 11 '22 06:12

1950


2 Answers

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.

like image 187
Johannes Kuhn Avatar answered Dec 25 '22 07:12

Johannes Kuhn


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++;
    }
}
like image 43
Elliott Frisch Avatar answered Dec 25 '22 08:12

Elliott Frisch