I am writing a war cards game. I need to shufle first few elements of players hand (linked list). That`s what i have:
void tasowanie(llist_t** head, int warsize) {
llist_t** temp = head;
Card_t temp_card;
int random;
while (warsize > 0) {
random = rand() % warsize;
for (int j = 0; j < random; j++)
if ((*temp)!=NULL && (*temp)->next != NULL)
*temp = (*temp)->next;
temp_card = (*head)->card;
(*head)->card = (*temp)->card;
(*temp)->card = temp_card;
*head = (*head)->next;
*temp = *head;
warsize--;
}
}
The problem is that I am losing elements of this list. I was thinking about puting these elements into array, then shufling it and puting it back to the list, although I imagine there has to be more elegant solution.
You should not be writing to *temp
, as this is a pointer to the real list next
pointer.
The same applies to moving head
: unless you intend to update the list you should not be touching *head
.
Instead, when you want to update temp
you should set it with temp = &((*temp)->next)
, and reset with temp=head
.
void tasowanie(llist_t** head, int warsize) {
llist_t** temp = head;
Card_t temp_card;
int random;
while (warsize > 0) {
random = rand() % warsize;
for (int j = 0; j < random; j++)
if ((*temp)!=NULL && (*temp)->next != NULL)
temp = &((*temp)->next);
temp_card = (*head)->card;
(*head)->card = (*temp)->card;
(*temp)->card = temp_card;
head = &((*head)->next);
temp = head;
warsize--;
}
}