-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhash.c
More file actions
55 lines (45 loc) · 1.25 KB
/
hash.c
File metadata and controls
55 lines (45 loc) · 1.25 KB
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
#include <stdlib.h>
#include <string.h>
#include "robosolver.h"
static hashEntry* table[1<<24];
static int match(location* robot, unsigned char* hashed) {
for (int i=0; i<4; i++) {
if (hashed[i]!=(unsigned char) robot[i])
return 0;
}
return 1;
}
static hashEntry* mkhash(location* robot, unsigned remainingDepth) {
hashEntry* entry = (hashEntry*) malloc(sizeof(hashEntry));
entry->next = NULL;
for (int i=0; i<4; i++) {
entry->robots[i] = (unsigned char) robot[i];
}
entry->remainingDepth = remainingDepth;
}
int lookup(location* robot, unsigned remainingDepth) {
unsigned hash = 0;
for (int i=0; i<4; i++) {
hash = 37*hash+robot[i];
}
hash &= (1<<24)-1;
if (!table[hash]) {
table[hash] = mkhash(robot, remainingDepth);
return 0;
}
hashEntry* entry = table[hash];
while (1) {
if (match(robot, entry->robots)) {
if (remainingDepth<=entry->remainingDepth) {
return 1;
}
entry->remainingDepth = remainingDepth;
return 0;
}
if (!entry->next) {
entry->next = mkhash(robot, remainingDepth);
return 0;
}
entry = entry->next;
}
}