-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
49 lines (39 loc) · 1.39 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
import { Examples, Solution } from '~types'
import { map, pipe, product, sum } from 'ramda'
export const parse = (input: string) => input.replace('\n', '').split(',')
const hash = (input: string) =>
input
.split('')
.map((c) => c.charCodeAt(0))
.reduce((acc, n) => ((acc + n) * 17) % 256, 0)
export const p1: Solution<typeof parse> = pipe(map(hash), sum)
type Lens = { label: string; focal: string }
type Box = Lens[]
export const p2: Solution<typeof parse> = (input) => {
const boxes = input
.map((seq) => seq.match(/(\w+)([=-])(\d)?/).slice(1) as string[])
.map((match) => [hash(match[0]), ...match] as string[])
.reduce(
(acc, [h, label, op, focal]) => {
let box: Box = acc[h] ?? []
if (op === '=') {
const i = box.findIndex((b) => b.label === label)
box[i === -1 ? box.length : i] = { label, focal }
}
if (op == '-') {
box = box.filter((b) => b.label !== label)
}
acc[h] = box
return acc
},
{} as Record<number, Box>,
)
return Object.entries(boxes)
.flatMap(([b, box]) => box.map(({ focal }, i) => [+b + 1, i + 1, +focal]))
.map(product)
.reduce((acc, n) => acc + n, 0)
}
export const p1ex: Examples = [
{ expected: 1320, input: 'rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7' },
]
export const p2ex: Examples = [{ expected: 145, input: p1ex[0].input }]