-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1000-sort_deck.c
112 lines (100 loc) · 1.85 KB
/
1000-sort_deck.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "deck.h"
/**
* sort_deck - sorts a deck of card
* @deck: doubly linked list to sort
*/
void sort_deck(deck_node_t **deck)
{
deck_node_t *curr;
size_t len;
deck_node_t *one, *two, *three, *four;
len = list_len_deck(*deck);
if (!deck || !*deck || len < 2)
return;
curr = *deck;
while (curr)
{
if (curr->prev && card_value(curr) < card_value(curr->prev))
{
one = curr->prev->prev;
two = curr->prev;
three = curr;
four = curr->next;
two->next = four;
if (four)
four->prev = two;
three->next = two;
three->prev = one;
if (one)
one->next = three;
else
*deck = three;
two->prev = three;
curr = *deck;
continue;
}
else
curr = curr->next;
}
}
/**
* card_value - returns the value of a card
* @node: card in a deck
*
* Return: value between 1 and 52
*/
int card_value(deck_node_t *node)
{
char *val[13] = {"Ace", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "Jack", "Queen", "King"};
char *kinds[4] = {"SPADE", "HEART", "CLUB", "DIAMOND"};
int i, kind_val = 0;
for (i = 1; i <= 13; i++)
{
if (!_strcmp(node->card->value, val[i - 1]))
kind_val = i;
}
for (i = 1; i <= 4; i++)
{
if (!_strcmp(kinds[node->card->kind], kinds[i - 1]))
kind_val = kind_val + (13 * i);
}
return (kind_val);
}
/**
* _strcmp - compares two strings
* @s1: first string to compare
* @s2: second string to compare
*
* Return: less than 0 if s1 is less than s2, 0 if they're equal,
* more than 0 if s1 is greater than s2
*/
int _strcmp(const char *s1, const char *s2)
{
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return (0);
}
s1++;
s2++;
}
return (*s1 - *s2);
}
/**
* list_len_deck - function returns length of list
* @list: head of list
*
* Return: length
*/
size_t list_len_deck(deck_node_t *list)
{
size_t len = 0;
while (list)
{
len++;
list = list->next;
}
return (len);
}