Is this code a good solution to randomise a two-dimensional array and write out all the
symbols on the screen? If you have a better tip or solution please tell me.
int slumpnr;
srand( time(0) );
char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};
for(int i = 0 ; i < 5 ; i++)
{
slumpnr = rand()%3;
if(slumpnr == 1)
{
cout << " " <<game[0][0] << " | " << game[0][1] << " | " << game[0][2] << "\n";
cout << "___|___|___\n";
}
else if(slumpnr == 0)
{
cout << " " << game[1][0] << " | " << game[1][1] << " | " << game[1][2] << "\n";
cout << "___|___|___\n";
}
else if(slumpnr == 3)
{
cout << " " << game[2][0] << " | " << game[2][1] << " | " << game[2][2] << "\n";
cout << "___|___|___\n";
}
}
system("pause");
}
You don’t need the if/else chain. Simply use the random variable as an index into your array:
Oh, I just noticed you have a weird mapping from 1 to 0 and from 0 to 1. If that is really necessary (for whatever reason), I would implement it like this:
And no, I do not have MSN or something, but here is a complete program to get you going.
Note however that this is not very random since you only pick from three different possible lines.