如何使数组不重复?

时间:2013-02-17 13:14:16

标签: c++ arrays random shuffle

这是我的简单游戏代码。粘贴并尝试。

#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行的最后,一些名称,动作和位置重复。如何让它们不重复并使用您将输入的每个名称?

2 个答案:

答案 0 :(得分:1)

使用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;

答案 1 :(得分:0)

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()相同的结果,但这是毫无根据的。

因此,你总有可能得到重复;事实上,每次你都会有1/64的机会获得相同的答案。

删除随机性,或在循环(as demonstrated by Mr @Eladidan)之前执行随机数组shuffle。或者,创建数字0,1,2,3的数组,随机 ,然后将其用作数据数组的索引。

随机改组(而非随机提取)的性质会给你一个不重复的答案。