// Shuffle can read in a small deck of cards
// It will partially shuffle that deck
// then print out the new ordering of those cards
// Marc Chee (cs1511@cse.unsw.edu.au), October 2020
#include <stdio.h>
#define MAX_DECK_SIZE 52
int readInput(int deck[MAX_DECK_SIZE]);
void printDeck(int deck[MAX_DECK_SIZE], int currentDeckSize);
void swap(int *card1, int *card2);
void shuffle(int deck[MAX_DECK_SIZE], int currentDeckSize);
int main(void) {
int deck[MAX_DECK_SIZE] = {0};
int deckSize = readInput(deck);
shuffle(deck, deckSize);
printDeck(deck, deckSize);
}
// Read the input and store it in the array
// returns the exact number of cards read in
int readInput(int deck[MAX_DECK_SIZE]) {
// ask the user how many cards there are
printf("How many cards are you entering?\n");
int num_cards = -1;
scanf("%d", &num_cards);
// loop through and scan in the cards
int i = 0;
while (i < num_cards && i < MAX_DECK_SIZE) { // have read i cards
// write each number scanned into the array
scanf("%d", &deck[i]);
i++;
} // have read i cards
return i;
}
// print out the cards in the deck
void printDeck(int deck[MAX_DECK_SIZE], int currentDeckSize) {
int i = 0;
while (i < currentDeckSize) {
printf("%d ", deck[i]);
i++;
}
printf("\n");
}
// Shuffle will call the swap function multiple times
// on the deck
void shuffle(int deck[MAX_DECK_SIZE], int currentDeckSize) {
int i = 0;
while (i < currentDeckSize) {
// otherCard is just a made-up way of
// grabbing another "random" card
int otherCard = (i * 2) % currentDeckSize;
swap(&deck[i], &deck[otherCard]);
i++;
}
}
// Swaps the values stored in integers that
// card1 and card2 point at
void swap(int *card1, int *card2) {
int temp = *card1;
*card1 = *card2;
*card2 = temp;
}
Resource created Friday 09 October 2020, 01:29:37 PM.
file: shuffle.c