卡片(节点)的甲板(链接列表)Riffle Shuffle

时间:2014-03-28 05:38:36

标签: c++ linked-list shuffle dynamic-allocation

我又回来了。因此,我使用卡片作为节点,以链接列表方式创建了一张卡片组。然而,我的riffle shuffle功能遇到了麻烦。该函数应该创建两个Deck对象,每个对象存储我的Deck drawPile的一半。那两个半桩应该一次取出一张牌并将其添加回drawPile。我没有收到错误,但根本不是洗牌。我这样称呼函数:drawPile.shuffle(drawPile);

Deck::Deck()
{
    top = NULL;
    SIZE = 0;
}

Deck::Deck(Card *n)
{
    top = n;
}
void Deck::shuffle(Deck &d)
{
    srand((unsigned)time(0));

    for (int i = 0; i < 7; i++){
        //split deck in half -- leftHalf and rightHalf
        Deck leftHalf, rightHalf;

        int j = SIZE/2;
        for (int k = SIZE; k > j; k--){
            drawCard(leftHalf);  //drawCard off Deck and addCard to leftHalf
        }
        for (j; j > 0; j--){
            drawCard(rightHalf);  //drawCard off Deck and addCard to rightHalf
        }
        while (leftHalf.getSIZE() > 0 && rightHalf.getSIZE() > 0){
            int probPile = leftHalf.getSIZE()/(leftHalf.getSIZE() + rightHalf.getSIZE())*100;
            int randomNum = rand() % 100 + 1;
            if (randomNum <= probPile){
                leftHalf.drawCard(d);   //drawCard off leftHalf and addCard to Deck
            }
            else{
                rightHalf.drawCard(d);  //drawCard off rightHalf and addCard to Deck
            }
        }
        while (leftHalf.getSIZE() > 0){
    leftHalf.drawCard(d);
        }
    while (rightHalf.getSIZE() > 0){
    rightHalf.drawCard(d);
    }
    }
}

void Deck::drawCard(Deck &d)    
{
    Card *draw = top;
    if (draw != NULL){
        top = top->getNext();
        SIZE--;
            d.addCard(draw->getVALUE(), draw->getSUIT());
    }
}//end drawCard

void Deck::addCard(int val, string s)
{
    top = new Card(val, s, top);
    SIZE++;
}//end addCard

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

while (leftHalf.getSIZE() > 0 && rightHalf.getSIZE() > 0){

如果您从leftHalf中抽取了所有卡片,但rightHalf仍然包含一些卡片,则您的周期结束。在这种情况下,您的混洗Deck不包含所有卡片 在那个循环之后,你需要例如实现两个循环:

while (leftHalf.getSIZE() > 0)
    // Draw all remaining cards from leftHalf
while (rightHalf.getSIZE() > 0)
    // Draw all remaining cards from rightHalf

============================================= <无线电通信/> 此外,您还可以在此处获得“空指针访问”错误:

d.addCard(draw->getVALUE(), draw->getSUIT());

因为draw可以为空。

============================================= <无线电通信/> 还在这里:

for (int l = SIZE; l > 0; l--){

你试图画太多牌。您可以从j而不是SIZE开始循环。

============================================== <登记/> 另一个问题是:

int probPile = leftHalf.getSIZE()/(leftHalf.getSIZE() + rightHalf.getSIZE())*100;

probPile始终为0,因为您使用整数除法(例如,如果我们使用整数除法,则5/100为0)。使用的解决方案之一 浮点除法。您可以在分割之前将int值转换为double,例如乘以1.0,然后将结果转换回int

int probPile = static_cast<int>(leftHalf.getSIZE() * 1.0 /(leftHalf.getSIZE() + rightHalf.getSIZE())*100);

或者你可以在分裂前乘以100:

int probPile = leftHalf.getSIZE() * 100/(leftHalf.getSIZE() + rightHalf.getSIZE());