Joakim
Joakim

Reputation: 165

Change value in boolean array. Choose place not value

I'm not sure this is possible. I'm building a program to choose a lotto row. I have a for loop to random pick seven numbers from 1 to 35. My plan is that i can make a boolean array and then take one of the random numbers to choose a place (not a value) in the boolean array and change it to True.

In this way I have the row number and I'm sure that the number is taken when the array place I true.

import java.util.Random; {


public static void main(String[] args) {
    int randomNr;
    boolean[] lottoRow = new boolean[35];

    Random randNr = new Random();

    for(int i=0; i<7; i++) {
        randomNr = randNr.nextInt(35)+1;

    }
}

How would i do this? Is it even a good way to approach this problem?

Upvotes: 1

Views: 192

Answers (2)

Glains
Glains

Reputation: 2863

A different appoach would be to generate the numbers directly without the need of a boolean[].

Set<Integer> numbers = new HashSet<>();
Random random = new Random();

for (int i = 0; i < 6; i++) {
    int number = getNextNumber(random);
    // we can get the same number twice
    while (numbers.contains(number)) {
        number = getNextNumber(random);
    }
    numbers.add(number);
}

With getNextNumber() being defined as:

public int getNextNumber(Random random) {
    return random.nextInt(35) + 1;
}

I find it simpler to generate the values directly rather than storing booleans in an array. In the end, you only need to know which numbers are drawn, not which numbers are not drawn.

Also, your solution does not account duplicte numbers, so the same number may be drawn mutliple times. To prevent that, you would have to either iterate through the array n times, or store the already drawn numbers. This is exactly the solution above and its faster.

Upvotes: 1

Mark
Mark

Reputation: 5239

You can use array[index] for this:

for (int i = 0; i < 7; i++) {
    randomNr = randNr.nextInt(35) + 1;
    lottoRow[randomNr - 1] = true;
}

This will assign the index (you call it place in your question) randomNr - 1 of lottoRow to true. Note that I added - 1 since arrays are 0-indexed.

Upvotes: 3

Related Questions