Issue
void putTile(int &n1, int &n2, int &n3, int &n4, int &n5, int &n6, int &n7, int &n8, int &n9)
{
srand(time(0));
int i = (((rand()%10)) < 5 ? 2:4);
if (n1||n2||n3||n4||n5||n6||n7||n8||n9 == 0) {
switch((rand()%9) + 1) {
case 1:
n1 = i;
break;
case 2:
n2 = i;
break;
case 3:
n3 = i;
break;
case 4:
n4 = i;
break;
case 5:
n5 = i;
break;
case 6:
n6 = i;
break;
case 7:
n7 = i;
break;
case 8:
n8 = i;
break;
case 9:
n9 = i;
break;
}
}
}
I am trying to generate either 2 or 4 at empty places(places containing 0) randomly, but my algorithm inputs randomly generated numbers (2 or 4) at random places even at places having a number already, as I have used the if statement at the beginning of the code. Any suggestions on how to correct the code?
Solution
There's a few issues which the comments already point out. Firstly, your if
statement doesn't work the way you expect. It is checking to see if n1
through n8
is not zero, or if n9
is zero.
Secondly, after the initial if statement, you just randomly change a position, but don't check if that value is non-zero.
A possible solution is:
void putTile( int &n1, int &n2, int &n3, int &n4, int &n5, int &n6, int &n7, int &n8, int &n9 ) {
int i = ( ( ( rand() % 10 ) ) < 5 ? 2 : 4 );
if ( n1 == 0 || n2 == 0 || n3 == 0 || n4 == 0 || n5 == 0 || n6 == 0 || n7 == 0 || n8 == 0 || n9 == 0 ) {
while ( true ) {
switch ( ( rand() % 9 ) + 1 ) {
case 1:
if ( n1 == 0 ) {
n1 = i;
return;
}
break;
case 2:
if ( n2 == 0 ) {
n2 = i;
return;
}
break;
case 3:
if ( n3 == 0 ) {
n3 = i;
return;
}
break;
case 4:
// ...
}
}
}
Note, this isn't very efficient, and has a lot of duplication. I would suggest using arrays.
Answered By - ChrisMM