-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
90 lines (85 loc) · 1.73 KB
/
index.ts
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
import run from 'aocrunner'
import * as util from '../utils/index.js'
const parseInput = (rawInput: string) =>
rawInput
.trim()
.split('\n')
.map((v) => {
const [dir, steps] = v.split(' ')
return [dir, +steps] as ['L' | 'R' | 'U' | 'D', number]
})
const simulateRope = (
input: ReturnType<typeof parseInput>,
tailKnots: number
) => {
const head: [number, number] = [0, 0]
const tails: [number, number][] = []
for (let t = 0; t < tailKnots; t++) {
tails.push([0, 0])
}
const tailGrids = new Set(['0:0'])
for (const [dir, steps] of input) {
for (let s = 0; s < steps; s++) {
const index = dir === 'L' || dir === 'R' ? 0 : 1
const delta = dir === 'L' || dir === 'U' ? -1 : 1
head[index] += delta
for (let t = 0; t < tails.length; t++) {
const follow = t === 0 ? head : tails[t - 1]
const hDist = follow[0] - tails[t][0]
const vDist = follow[1] - tails[t][1]
if (Math.abs(hDist) > 1 || Math.abs(vDist) > 1) {
tails[t][0] += util.clamp(hDist, -1, 1)
tails[t][1] += util.clamp(vDist, -1, 1)
if (t === tails.length - 1) tailGrids.add(tails[t].join(':'))
}
}
}
}
return tailGrids
}
const part1 = (rawInput: string) => {
const input = parseInput(rawInput)
const tailGrids = simulateRope(input, 1)
return tailGrids.size.toString()
}
const part2 = (rawInput: string) => {
const input = parseInput(rawInput)
const tailGrids = simulateRope(input, 9)
return tailGrids.size.toString()
}
run({
part1: {
tests: [
{
input: `R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2`,
expected: '13',
},
],
solution: part1,
},
part2: {
tests: [
{
input: `R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20`,
expected: '36',
},
],
solution: part2,
},
trimTestInputs: true,
// onlyTests: true,
})