2010-10-23 96 views
0

此代码是一个很好的解决方案,可以随机化一个二维数组并写出屏幕上所有的 符号吗?如果您有更好的提示或解决方案,请告诉我。randomise一个二维数组与字符?

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"); 
} 
+0

[randomise a two-dimensional array?]的可能重复?(http://stackoverflow.com/questions/4003814/randomise-a-two-dimensional-array) – 2010-10-23 14:44:27

+0

的确如此。 – 2010-10-23 14:46:17

+0

即使用户发布了上一个问题,也是一样的。 @Nelly - 您可以编辑您以前的问题。 – 2010-10-23 14:51:52

回答

2

您不需要if/else链。只需使用随机变量作为索引到你的数组:

int r = rand() % 3; 
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n"; 
cout << "___|___|___\n"; 

哦,我只注意到你有1一个奇怪的映射为0,从0到1,如果是真的有必要(无论何种原因),我想实现这样的:

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"; 

不,我没有MSN什么的,但这里是一个完整的程序,让你去。

#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"); 
} 

但请注意,这不是很随机,因为你只从三个不同的可能的行中选择。

+0

你能帮我把这段代码写进我的代码吗?因为我不明白如何投入我的职能。 – Atb 2010-10-23 15:35:00

+0

你有MSN吗?因为我真的需要完成我的代码,我吮吸C++:/ – Atb 2010-10-23 15:36:29

+0

好的非常感谢你帮助我。我真的很感谢! – Atb 2010-10-23 15:44:20

0

除了最后如果这应该是:

if(slumpnr == 2) // 2 instead of 3 

一切正常。你正在初始化随机序列(注意在启动时只做一次),所以你应该随机选择一台电脑。

+1

不是最好的。例如在一个16位的机器上,'(rand()%3)'稍微偏向于返回一个'0'。虽然这个偏差只有0.005%左右! – 2010-10-23 14:49:49