randomise a two-dimensional array with chars?
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) );
ch开发者_JAVA百科ar 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:
int r = rand() % 3;
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";
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:
static const int mapping[] = {1, 0, 2};
int r = mapping[rand() % 3];
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";
And no, I do not have MSN or something, but here is a complete program to get you going.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};
for (int i = 0; i < 5; ++i)
{
int r = rand() % 3;
std::cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
std::cout << "___|___|___\n";
}
system("pause");
}
Note however that this is not very random since you only pick from three different possible lines.
Except the last if that should be:
if(slumpnr == 2) // 2 instead of 3
Everything looks ok. You are correctly initializing random sequence (take care to do it once only at startup), so you should get best random a computer can do.
精彩评论