Mavix
Mavix

Reputation: 181

Method for avoiding duplicates when generating a random list of pairs of numbers is not working as it should

I have this code for setting random values to true in a boolean[][], without making any duplicates:

    int a = 0;
    int b = 0;
    int counter = 0;

    for (int i=0; i<=50; i++) {                                         
        do {
            a = randomizer.nextInt(hoogte);                                 
            b = randomizer.nextInt(breedte);    
            /**debug variable*/
            counter++;
        } while (bommaker[a][b]);

        bommaker[a][b] = true; 
    }

After testing for a while, I noticed something was wrong, so I added a counter to check it. Every time I run the program, there comes a different number out of "counter". One time it was 57 while the other time even 63. But I have set the loop to exactly 51. This means the code isn't working as it should. Can somebody explain why it generates more than 51 numbers, and give a possible solution?

Upvotes: 0

Views: 160

Answers (2)

Riskhan
Riskhan

Reputation: 4470

move out the counter++ line from do while loop

int a = 0;
int b = 0;
int counter = 0;

for (int i=0; i<=50; i++) {                                         
    do {
        a = randomizer.nextInt(hoogte);                                 
        b = randomizer.nextInt(breedte);    
        /**debug variable*/
    } while (bommaker[a][b]);

    counter++;

    bommaker[a][b] = true; 
}

Upvotes: 0

John B
John B

Reputation: 32969

You have to remember that you have a loop within a loop. The OUTTER loop is limited to 51 executions, but the inner loop will cause a random number of iterations (an extra iteration for each time it sees that the array has already been set to true).

Other than the counter value being greater than you expected, what about the code is not working?

Upvotes: 4

Related Questions