-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwelve.js
104 lines (91 loc) · 2.24 KB
/
twelve.js
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
const { readFile } = require('fs/promises');
const GRID = [];
const BEST = [];
const ALL_BEST = [];
let endX, endY;
// 12
async function init() {
const input = (await readFile('twelve.txt', 'utf8')).split('\n');
// const input = (await readFile('twelve.test.txt', 'utf8')).split('\n');
let x, y;
input.forEach((row, i) => {
GRID[i] = [];
row.split('').forEach((d, j) => {
GRID[i][j] = d;
if (d === 'S') {
y = i;
x = j;
GRID[i][j] = 'a';
} else if (d === 'E') {
endX = j;
endY = i;
GRID[i][j] = 'z';
}
});
});
// console.log(GRID.join('\n'));
console.time('a');
GRID.forEach((row, i) => {
row.forEach((d, j) => {
if (d === 'a') {
x = j;
y = i;
console.time('b');
// reset the BEST
GRID.forEach((row, i) => {
BEST[i] = [];
});
findNext({ x, y }, 0);
console.timeEnd('b');
if (BEST[endY][endX]) {
ALL_BEST.push(BEST[endY][endX]);
}
}
});
});
console.timeEnd('a');
console.log(ALL_BEST.sort());
}
function findNext({ x, y }, count) {
if (x === endX && y === endY) {
// at the finish line
if (!BEST[y][x] || count < BEST[y][x]) {
BEST[y][x] = count;
}
} else if (!BEST[y][x] || count < BEST[y][x]) {
// still looking
BEST[y][x] = count;
const charCode = GRID[y][x].charCodeAt(0);
let nextCharCode;
// check right
if (x + 1 < GRID[0].length) {
nextCharCode = GRID[y][x + 1].charCodeAt(0);
if (nextCharCode - charCode <= 1) {
findNext({ x: x + 1, y }, count + 1);
}
}
// check down
if (y + 1 < GRID.length) {
nextCharCode = GRID[y + 1][x].charCodeAt(0);
if (nextCharCode - charCode <= 1) {
findNext({ x, y: y + 1 }, count + 1);
}
}
// check up
if (y - 1 >= 0) {
nextCharCode = GRID[y - 1][x].charCodeAt(0);
if (nextCharCode - charCode <= 1) {
findNext({ x, y: y - 1 }, count + 1);
}
}
// check left
if (x - 1 >= 0) {
nextCharCode = GRID[y][x - 1].charCodeAt(0);
if (nextCharCode - charCode <= 1) {
findNext({ x: x - 1, y }, count + 1);
}
}
}
// not the best :)
}
init();