как я могу реализовать 5-карточный обратный Fisher–Yates_shuffle на C?
Я использую это как руководство, но думаю, что с моей реализацией что-то не так.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>
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[])
{
assert(deck != NULL);
for (unsigned int cardIndex = 0; cardIndex < NUM_CARDS_IN_HAND; cardIndex++)
{
unsigned int random = GetRandomNumber(NUM_CARDS_IN_DECK - cardIndex);
while (random < cardIndex) random = GetRandomNumber(NUM_CARDS_IN_DECK - cardIndex); // random must be greater or equal to cardIndex
const Card temp = deck->cards[cardIndex];
deck->cards[cardIndex] = deck->cards[random];
deck->cards[random] = temp;
}
}