[英]How to make an array to not repeat?
這是我的簡單游戲代碼。 粘貼並嘗試。
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (void)
{
string g[4],
b[4],
a[4],
l[4];
srand((unsigned int)time(0));
cout << "Welcome!\n\n";
cout << "Type 4 girl names.\n";
for (int gi = 0; gi < 4; gi++)
cin >> g[gi];
cout << "Type 4 boy names.\n";
for (int bi = 0; bi < 4; bi++)
cin >> b[bi];
cout << "\nWhat they do (enter 4 actions)?\n";
for (int ai = 0; ai < 4; ai++)
getline(cin, a[ai]);
cout << "\nWhere is happening (enter 4 locations)?\n";
for (int li = 0; li < 4; li++)
getline(cin, l[li]);
for (int c = 0; c < 4; c++)
cout << g[rand() % 4] << " and " << b[rand() % 4] << " are " << a[rand() % 4] << " from a " << l[rand() % 4] << endl;
return (0);
}
在第4行的末尾,重復了一些名稱,動作和位置。 如何使他們不再重復使用您輸入的每個名稱?
使用std::random_shuffle
:
std::random_shuffle(g, g + 4);
std::random_shuffle(b, b + 4);
std::random_shuffle(a, a + 4);
std::random_shuffle(l, l + 4);
然后,只需遍歷所有改組后的數組即可:
for (int c = 0; c < 4; c++)
cout << g[c] << " and " << b[c] << " are " << a[c] << " from a " << l[c] << endl;
for (int c = 0; c < 4; c++)
cout << g[rand() % 4] << " and " << b[rand() % 4] << " are "
<< a[rand() % 4] << " from a " << l[rand() % 4] << endl;
您已經做出假設,保證對rand()
連續調用不會產生與之前對rand()
調用相同的結果,但這是毫無根據的。
因此,總是有重復的可能。 實際上,您有64次機會中有1次您每次都會得到相同的答案 。
要么刪除隨機性,要么在循環之前執行隨機數組隨機播放( 如@Eladidan先生所展示的 )。 或者,創建數字陣列0,1,2,3
, 混洗,然后用它作為索引到你的數據數組。
這是隨機改組 (而不是隨機抽取 )的本質,它會給您一個非重復的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.