1

我正在尝试创建一个随机从牌组中抽牌的程序。问题是我需要使抽奖过程实际上是随机的,因为在没有其他因素改变的情况下使用 srand 和 rand 时每次抽奖都是相同的。因此,我将它附加到 time_t 秒,并且能够使绘制半/随机。这是因为我必须等待一秒钟才能改变 time_t 秒的参数。这是一个问题的原因是,如果我的程序两次抽取同一张牌(这是众所周知的),我的程序就会再次抽取。因此,如果它确实抽了两次同一张牌,它将被迫再抽大约 15 次(或多或少),直到 time_t 第二个参数发生变化。有没有办法测量毫秒或更小的时间单位,所以我没有这个问题?

这是代码,尽管没有附加检查匹配和组织过程(无论如何,这些只发生在初始抽签之后。)

int allow = 0;
    string cards[] = 
    {"02hearts", "03hearts", "04hearts", "05hearts", "06hearts", "07hearts", "08hearts","09hearts", "10hearts", "11hearts", "12hearts", "13hearts", "14hearts",
     "02clubs", "03clubs", "04clubs", "05clubs", "06clubs", "07clubs", "08clubs", "09clubs", "10clubs", "11clubs", "12clubs","13clubs", "14clubs","14clubs", 
    "02spades", "03spades", "04spades", "05spades", "06spades", "07spades", "08spades", "09spades", "10spades", "11spades", "12spades", "13spades", "14spades",
    "02diamonds", "03diamonds", "04diamonds", "05diamonds", "06diamonds", "07diamonds", "08diamonds", "09diamonds", "10diamonds", "11diamonds", "12diamonds", "13diamonds", "14diamonds"};
    string cardHand [5];
    string cardnumbers [5];
    int cardInts [5];
    string handSuites [5];
    char handSuitesChar [5];





    //check deck
    while(allow == 0)
    {

    //set clock
    time_t seconds;

    time(&seconds);


    srand((unsigned int) seconds);

    int type;

    //initiate counters
    int n = 0;
    int n1 = 0;
    int n2 = 0;
    int n3 = 0;
    int n4 = 0;

    //draw cards
    while(n < 5)
    {
        type = rand() % 52;
        cardHand[n] = cards[type];
        cout << cardHand[n] << ", ";
        n++;
    }


    cout << endl;

    //pull numbers from cards
    while(n1 < 5)
    {
        string character2;
        cardnumbers[n1] = cardHand[n1].at(0);
        character2 = cardHand[n1].at(1);
        cardnumbers[n1].append(character2);
        cout << cardnumbers[n1] << ", ";
        n1++;
    }
    cout << endl;
    cout << endl;


    //convert numbers to ints
    while(n2 < 5)
    {
        stringstream convert(cardnumbers[n2]);

        if( !(convert >> cardInts[n2]))
            cardInts[n2] = 0;

        cout << cardInts[n2] + 100 << ", ";

        n2++;
    }

    cout << endl;

    //pull out first letters for suites
    while (n3 < 5)
    {
        handSuites[n3] = cardHand[n3].at(2);

        cout << handSuites[n3]<< endl;
        n3++;
    }


    //convert letters to chars
    while (n4 < 5)
    {
        stringstream convert(handSuites[n4]);

        if( !(convert >> handSuitesChar[n4]))
            handSuitesChar[n4] = 0;

        cout << handSuitesChar[n4] + 100 << ", ";
        n4++;
    }
4

2 回答 2

4

不要srand()在循环内调用。在程序开始时调用一次,然后rand()在需要随机数时使用。这会给你一个相当长的伪随机序列。

于 2012-12-12T21:02:04.060 回答
0

正如 Rob 所指出的,问题不在于rand(),而在于你抽牌的方式。没有理由每次都抽同一张牌两次。你可以使用 Rob 的建议,然后洗牌,也可以从未洗牌的牌组中随机挑选一张牌,然后将其从牌组中移除(与末端交换,然后pop_back),这样就不能再抽了。

当然,永远不要在一个进程中多次为生成器播种。

于 2012-12-12T22:09:38.997 回答