2010-10-23 95 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