-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.js
75 lines (68 loc) · 1.48 KB
/
day2.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
import {
always,
applySpec,
compose,
equals,
identity,
includes,
map,
prop,
split,
} from 'ramda';
import { read } from '../../../lib/read.js';
const data = read(`${import.meta.dirname}/input.txt`);
const prepare = compose(map(compose(split(''))), split('\n'));
const directions = {
U: [-1, 0],
R: [0, 1],
D: [1, 0],
L: [0, -1],
};
const positionOf = (value, keypad) => {
const row = keypad.findIndex(includes(value));
return [row, keypad[row].findIndex(equals(value))];
};
const findCode = compose(prop('code'), ({ groups, keypad }) =>
groups.reduce(
({ code, pos }, instructions) => {
instructions.forEach(instruction => {
const dir = directions[instruction];
pos[0] = keypad[pos[0] + dir[0]]?.[pos[1]] ? pos[0] + dir[0] : pos[0];
pos[1] = keypad[pos[0]]?.[pos[1] + dir[1]] ? pos[1] + dir[1] : pos[1];
});
return {
pos,
code: code + keypad[pos[0]][pos[1]],
};
},
{ code: '', pos: positionOf(5, keypad) },
),
);
const part1 = compose(
findCode,
applySpec({
groups: identity,
keypad: always([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]),
}),
prepare,
);
const part2 = compose(
findCode,
applySpec({
groups: identity,
keypad: always([
[0, 0, 1, 0, 0],
[0, 2, 3, 4, 0],
[5, 6, 7, 8, 9],
[0, 'A', 'B', 'C', 0],
[0, 0, 'D', 0, 0],
]),
}),
prepare,
);
console.log('part 1', part1(data));
console.log('part 2', part2(data));