forked from vanessayuenn/advent-of-code-2016
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday17.js
49 lines (43 loc) · 1.2 KB
/
day17.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
const md5 = require('./md5.min.js');
const input = `ioramepc`;
let path = [];
const isOpen = (ch) => ['b','c','d','e','f'].includes(ch);
const isValidMove = (x, y) => x > -1 && x < 4 && y > -1 && y < 4;
const dir = ['U','D','L','R'];
const newPos = (x, y, dir) => {
switch (dir) {
case 'U':
return [x, y-1];
case 'D':
return [x, y+1];
case 'L':
return [x-1, y];
case 'R':
return [x+1, y];
default:
return;
}
}
const move = (x, y, str) => {
let hash = (md5(str)).substr(0, 4);
if (x === 3 && y === 3) {
path.push(str.substr(input.length));
return;
}
for (let i = 0; i < hash.length; i++) {
if (isOpen(hash[i])) {
let [x2, y2] = newPos(x, y, dir[i]);
if (isValidMove(x2, y2)) {
move(x2, y2, str+dir[i]);
}
}
}
}
move(0, 0, input);
console.log('--------------- PART 1 ---------------');
const shortest = path.reduce((a, b) => a.length < b.length ? a : b);
console.log(`Shortest path is ${shortest}.`);
console.log('--------------- PART 2 ---------------');
const longest = path.reduce((a, b) => a.length > b.length ? a : b);
console.log(`Longest path is ${longest}.`);
console.log(`It contains ${longest.length} steps.`);