-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaster_mind.c
139 lines (100 loc) · 2.18 KB
/
master_mind.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include "lib/hash.h"
struct IndexInfo
{
int index;
int hit;
int pseudo_hit;
struct ListNode hook;
};
void IndexInfoInit(struct IndexInfo *index_info, int index)
{
index_info->index = index;
index_info->hit = 0;
index_info->pseudo_hit = 0;
ListNodeInit(&index_info->hook, index_info);
}
void AddIndexToList(struct ListNode *list, int index)
{
struct IndexInfo *index_info = calloc(1, sizeof(struct IndexInfo));
IndexInfoInit(index_info, index);
ListAddTail(list, &index_info->hook);
}
void CalculateHit(struct ListNode *list, int index, int *hit, int *pseudo_hit)
{
struct ListNode *head = list, *p = NULL;
struct IndexInfo *index_info = NULL;
for (p = head->next; p != head; p = p->next)
{
index_info = p->container;
if (index_info->index == index)
{
if (index_info->pseudo_hit == 1)
--*pseudo_hit;
ListNodeDelete(p);
++*hit;
return;
}
}
if (index_info == NULL)
return;
if (index_info->pseudo_hit == 0)
{
index_info->pseudo_hit = 1;
++*pseudo_hit;
}
}
void PrepareSolution(struct Hash *hash, char *solution)
{
char *s = solution;
int index = 0;
while (*s != '\0')
{
struct ListNode *list = NULL;
int key = *s - 'A';
if ((list = HashGet(hash, &key)) == NULL)
{
int *new_key = calloc(1, sizeof(int));
list = calloc(1, sizeof(struct ListNode));
*new_key = key;
ListInit(list);
HashInsert(hash, new_key, list);
}
AddIndexToList(list, index);
++index;
++s;
}
}
void CheckGuess(struct Hash *hash, char *guess)
{
char *g = guess;
int index = 0;
int hit = 0, pseudo_hit = 0;
while (*g != '\0')
{
struct ListNode *list = NULL;
int key = *g - 'A';
if ((list = HashGet(hash, &key)) != NULL)
CalculateHit(list, index, &hit, &pseudo_hit);
++index;
++g;
}
printf("hit %d pseudo_hit %d\n", hit, pseudo_hit);
}
void PrintResults(char *solution, char *guess)
{
struct Hash hash;
HashInit(&hash, FuncIntToInt, FuncIntCompare);
PrepareSolution(&hash, solution);
CheckGuess(&hash, guess);
}
int main(int argc, char *argv[])
{
char solution[] = "RGBY";
char guess[] = "GGRR";
PrintResults(solution, guess);
return 0;
}