How to shuffle/randomize a linked list in C? I am currently creating an UNO game
ID: 3710883 • Letter: H
Question
How to shuffle/randomize a linked list in C?
I am currently creating an UNO game in C. I have to use a linked list to create the deck (consisting of 108 cards). I need to implement a shuffle function to randomly shuffle the deck, but i am pretty lost on where to start.
Here is a picture of the code I have so far.
#include 10 #include 12 typedef struct card s f 13 14 15 16 17card; 18 19 void print_list(card headp) char suit [71; int value; char action[15]; struct card s *pt (headp printf("%s %d headp while NULL){ %s != ", headp->suit, headp->value, headp->action); headp->pt; = printf("n" 25 28 29 int main(void) 30 int choice; card?eadp=NULL, FILE *fp 32 *temp , *tail=NULL; 35 fpfopen("Uno_Deck.txt", "r"); (card)); *)malloc(sizeof "%s NULL){ temp (card = while %d temp->suit, &temp-;>value, temp->action) EOF){ (fscanf(fp, if 38 %s", != (head p = 40 headp temp ; else tail = temp ; tail->pt = NULL; temp(card *) malloc(sizeof (card)); 45 fclose(fp); printf("Let's Play a Game of UNO "); printf("Press 1 to shuffle the UNO deck or 2 to load a deck from a file: "); scanf ( "%d", &choice;); if (choice 1)( 52 if (choice2) printf("The deck has been loaded in. "; print list (headp); return 8Explanation / Answer
There are many possible ways to shuffle a linked list, one of such approach is:
- Run a loop from 0 to 107
- In each iteration i generate a random number r between i to 107. Now move that node in the front of the list:
[This is similar to deleting rth node and copying the same in the front]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.