Can someone please explain this function? int deckshuffle() { card *y; card *z;
ID: 3573692 • Letter: C
Question
Can someone please explain this function?
int deckshuffle() {
card *y;
card *z;
card *temp;
int r;
int i;
int u;
int t;
temp = (card *)malloc(sizeof(card)); // allocates memory for the node temp
for (i = 0; i<52; i++){
r = rand() % 52; //divides random number into 52
y = crd;
z = crd;
for (u = 0; u < r; u++) {
y = y->listp; // points y to the list of the cards one by one
}
for (t = 0; t < i; t++) { // loop for swtitching posistions of cards in the list
z = z->listp;
}
temp->face = z->face;
temp->suit = z->suit;
z->face = y->face;
z->suit = y->suit;
y->face = temp->face;
y->suit = temp->suit;
}
}
Explanation / Answer
//A function used to shuffle the deck of cards.
//Assuming card is a structure which has already been declared.
int deckshuffle()
{
card *y; //y is a pointer of type card.
card *z; //z is a pointer of type card.
card *temp; //temp is a pointer of type card.
int r; //All these are variables of type int.
int i;
int u;
int t;
temp = (card *)malloc(sizeof(card)); // allocates memory for the node temp
for (i = 0; i<52; i++) //For a total of 52 times.
{
r = rand() % 52; //Generates a random number between 0 and 51.
y = crd; //y is assigned a pointer crd, believe crd is a pointer to start of the list.
z = crd; //z is also pointing to head of the list.
for (u = 0; u < r; u++) //The pointer y moves forward randomly based on r value.
{
y = y->listp; // points y to the list of the cards one by one
}
for (t = 0; t < i; t++) //The pointer t moves forward i times.
{ // loop for swtitching posistions of cards in the list
z = z->listp;
}
//The random card is exchanged with ith card.
//Both its face value and suit value is swapped with one another.
temp->face = z->face;
temp->suit = z->suit;
z->face = y->face;
z->suit = y->suit;
y->face = temp->face;
y->suit = temp->suit;
}
}