0

我将此作为指南,但我认为我的实现有问题。 https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm

-- To shuffle an array a of n elements (indices 0..n-1):
for i from 0 to n−2 do
     j ← random integer such that i ≤ j < n
     exchange a[i] and a[j]

我正在尝试使用整个甲板作为一个池来洗牌的前 5 张牌,但只洗牌前 5 张牌。

这是我的代码:

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

enum { NUM_CARDS_IN_DECK = 52 };
enum { NUM_CARDS_IN_HAND = 5 };

typedef unsigned int Card;

typedef struct
{
    Card cards[NUM_CARDS_IN_DECK];
} Deck;

unsigned int GetRandomNumber(unsigned int range)
{
    if (range == 0) return UINT_MAX;

    /* Use division truncation to discover the largest number divisible by range. */
    const unsigned int randLimit = (RAND_MAX / range) * range;
    unsigned int number = randLimit;
    while (number >= randLimit) number = (unsigned int)rand();
    return number % range;
}

void ShuffleDeck(Deck deck[])
{
    for (unsigned int cardIndex = 0; cardIndex < NUM_CARDS_IN_HAND; cardIndex++)
    {
        unsigned int random = cardIndex + GetRandomNumber(NUM_CARDS_IN_DECK - cardIndex); // need random to be greater than cardIndex
        printf("\n %d \n", random);
        const Card temp = deck->cards[random];
        deck->cards[random] = deck->cards[cardIndex];
        deck->cards[cardIndex] = temp;
    }
}

int main(void) 
{
    Card cards[NUM_CARDS_IN_DECK] = { 0 };
    Deck deck = { cards };

    for (int index = 0; index < 5; index++) 
    {

        for (int index = 0; index < NUM_CARDS_IN_DECK; index++)
        {
            deck.cards[index] = index;
        }

        printf("\nstarting deck : ");
        for (int index = 0; index < NUM_CARDS_IN_DECK; index++)
        {
            if (index != 0) printf(" ,");
            printf("%d", deck.cards[index]);
        }
        printf("\n");


        ShuffleDeck(&deck);

        printf("\nshuffled deck : ");
        for (int index = 0; index < NUM_CARDS_IN_DECK; index++)
        {
            if (index != 0) printf(" ,");
            printf("%d", deck.cards[index]);
        }
        printf("\n");
    }
}

编辑:

您不需要 ShuffleDeck() 中的 while 循环,只需使用 random = cardIndex + GetRandomNumber(NUM_CARDS_IN_DECK - cardIndex) 并无条件交换。– G.斯莱彭

这实际上解决了我的问题。

4

0 回答 0