Joe Kohl
Joe Kohl

Reputation: 41

Trying to fill boolean matrix with random values

while(MatriceLib.compteTrue(champsMine)!= nbMines)
       {
          int i = (int) Math.floor((Math.random()*(longueur-1)));
          int j = (int)Math.floor((Math.random()*(largeur-1)));
          champsMine[i][j] = true;
} 

champsMine is the boolean matrix with booleran at random positions. compteTrue is returning an int value of the number of true in the matrix. nbMines is the number of true the matrix has to have.

The problem is that it takes a lot of time to populate the matrix with the values.

Is there a way to make it more efficient?

Upvotes: 1

Views: 383

Answers (1)

Jason C
Jason C

Reputation: 40356

You don't post a lot of code but it looks like you are counting the number of true elements in the array each time through the loop. This is the slow part. Instead, consider maintaining a count as you go, e.g.:

int count = 0; // or whatever the current count is, if there are already true elements
while (count < nbMines) {
    int i = ...;
    int j = ...;
    if (!champsMine[i][j]) {
        ++ count;
        champsMine[i][j] = true;
    }
}

Of course, this will slow down as the number of false slots remaining decreases (increasing the chance of random positions already being set). An alternate approach is to create an array/list of all (i,j) combinations (one for each cell in the grid), randomly shuffle this list, then take the first nbMines coordinates from that list and set those values to true. That is slightly more complex to set up, but still straightforward, and will be very fast (populating the list then shuffling it guarantees you won't pick coordinates that have already been set). It is also naturally safe against the possibility that nbMines is greater than the number of grid cells.

Upvotes: 4

Related Questions