how can I implement a 5 card reverse Fisher–Yates_shuffle in C?

70 Views Asked by At

I'm using this as a guide but I think something is wrong with my implementation. 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]

I'm trying to shuffle the first 5 cards of a deck using the whole deck as a pool to shuffle from, but only shuffling the first 5 cards.

here is my code:

#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");
    }
}

EDIT:

You shouldn't need the while-loop in ShuffleDeck(), just use random = cardIndex + GetRandomNumber(NUM_CARDS_IN_DECK - cardIndex) and swap unconditionally. – G. Sliepen

This acctually fixed my problem.

0

There are 0 best solutions below