generating random numbers

the following code in my mind should generate a random number without selecting the same one before:

1
2
3
4
5
6
7
8
9
10
11
12
13
void genRandNums(int &rRow,int &rCol)
{
    static map<int,bool> randRowsDone;
    static map<int,bool> randColsDone;

    randRowsDone.insert(pair<int,bool>(rRow, true));
    randColsDone.insert(pair<int,bool>(rCol, true));

    while (randRowsDone[rRow])
        rRow = rand() % 8 + 0;
    while (randColsDone[rCol])
        rCol = rand() % 8 + 0;
}


But it doesnt seem to do that, can you spot any errors?
Hello FinalFortune,

the operator[Key] creates a field with Key if the field doesn't exists. In your case it's an undefined bool which is usually true.

Since you generate numbers from 0 to 8 you can use a fixed size array
In your case it's a bool which is always false.

Fixed.

The problem here is that you're not crossing out the random numbers you generate, but rather the values rRow and rCol had before the function call.
Also, you should write
1
2
randRowsDone[rRow]=true;
randColsDone[rCol]=true;

instead of using insert.
Topic archived. No new replies allowed.