Created
May 13, 2014 22:20
-
-
Save zlalanne/df0494435e8853134276 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
typedef struct card { | |
unsigned int value; | |
struct card *next; | |
} Card_t; | |
static int AllocateCards(unsigned int numCards, Card_t **deckHead, Card_t **deckTail) { | |
unsigned int i; | |
for(i = numCards; i != 0; i--) { | |
Card_t *card = malloc(sizeof(Card_t)); | |
card->value = i; | |
card->next = *deckHead; | |
*deckHead = card; | |
if(i == numCards) { | |
*deckTail = card; | |
} | |
} | |
return 0; | |
} | |
static int FreeCards(Card_t **deckHead) { | |
while(*deckHead != NULL) { | |
Card_t *temp = *deckHead; | |
*deckHead = *(deckHead->next); | |
free(temp); | |
} | |
} | |
static bool CheckCardOrder(Card_t *deckHead) { | |
unsigned int i = 1; | |
bool match = true; | |
while(deckHead != NULL) { | |
if(deckHead->value != i) { | |
match = false; | |
break; | |
} | |
i++; | |
deckHead = deckHead->next; | |
} | |
return match; | |
} | |
int main(int argc, char **argv) { | |
unsigned int numCards; | |
if(argc != 2) { | |
printf("Error: Incorrect number of command line arguments\n"); | |
return 1; | |
} | |
if(sscanf(argv[1], "%i", &numCards) != 1) { | |
printf("Error: Command line argument is not an integer\n"); | |
return 1; | |
} | |
Card_t *deckHead = NULL; | |
Card_t *deckTail = NULL; | |
int status = AllocateCards(numCards, &deckHead, &deckTail); | |
Card_t *tableHead = NULL; | |
Card_t *tableTail = NULL; | |
bool match = false; | |
unsigned int rounds = 0; | |
while(!match) { | |
// Cycle through deck, stop once all cards are on table | |
while(deckHead != NULL) { | |
// Putting card on table | |
if(tableHead == NULL) { | |
tableHead = deckHead; | |
} | |
if(tableTail == NULL) { | |
tableTail = deckHead; | |
} else { | |
tableTail->next = deckHead; | |
tableTail = deckHead; | |
} | |
deckHead = deckHead->next; | |
tableTail->next = NULL; | |
// Exit if that was last card | |
if(deckHead == NULL) { | |
break; | |
} | |
// Putting card at bottom of deck | |
deckTail->next = deckHead; | |
deckHead = deckHead->next; | |
deckTail = deckTail->next; | |
deckTail->next = NULL; | |
} | |
rounds++; | |
match = CheckCardOrder(tableHead); | |
// Table is not in correct order, need to perform another round. Reset deck | |
if(!match) { | |
deckHead = tableHead; | |
deckTail = tableTail; | |
tableHead = NULL; | |
tableTail = NULL; | |
} | |
} | |
FreeCards(tableHead); | |
printf("%d", rounds); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment