-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboardhashing.cpp
More file actions
75 lines (62 loc) · 1.75 KB
/
Copy pathboardhashing.cpp
File metadata and controls
75 lines (62 loc) · 1.75 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "boardhashing.hpp"
template <int N>
void _flatten(const Board<N> &board, std::vector<int> &result) {
result.clear();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result.push_back(board.tiles[i][j]);
}
}
}
template <int N>
void _deflatten(const std::vector<int> &l, Board<N> &result) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result[i][j] = l[N*i+j];
}
}
}
// Board to BigInt hashing done in O(N^2 log^2 N) time, where N is board size.
//
// Btw, the log^2 N comes from BigInt multiplication
//
// If integer arithmetic always took constant time, we would have O(N^2 log N)
template <int N>
void board_hash(const Board<N> &board, BigInt &result) {
std::vector<int> s;
ordered_set t;
_flatten(board, s);
result.clear();
// Converts s (base factorial) to base 2^32 and stores the result in result
for (int i = 0; i < N*N; i++) {
BigInt b(factorial(N*N-i-1));
int order = (int)t.order_of_key(s[i]);
BigInt v = { (unsigned int)(s[i] - order - 1) };
t.insert(s[i]);
BigInt product;
mul(b, v, product);
BigInt temp(result);
add(temp, product, result);
}
}
int board_test() {
printf("Doing hashing test\n");
Board<5> board;
board.disp();
BigInt h;
board_hash<5>(board, h);
disp(h);
printf("Moving col 0 UP\n");
board.do_move(Up, 0);
board.disp();
printf("Doing hashing test with slightly different board\n");
board_hash<5>(board, h);
disp(h);
printf("Moving row 2 RIGHT\n");
board.do_move(Right, 2);
board.disp();
printf("Recalculating hash...\n");
board_hash<5>(board, h);
disp(h);
return 0;
}