-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
82 lines (76 loc) · 1.76 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
import run from 'aocrunner'
const parseInput = (rawInput: string) => {
const [stacks, instructions] = rawInput.split('\n\n')
const rows = stacks.split('\n')
rows.pop()
const colCount = Math.ceil((rows[0].length + 1) / 4)
const stackArr: string[][] = []
for (let col = 1; col <= colCount; col++) {
stackArr[col] = []
for (const row of rows) {
const crate = row.split('')[1 + (col - 1) * 4]
if (crate.trim()) stackArr[col].unshift(crate)
}
}
return {
stacks: stackArr,
instructions: instructions.split('\n').map((inst) => {
const [first, last] = inst.split(' from ')
const [_, count] = first.split('move ')
const [from, __, to] = last.split(' ')
return { count: +count, from: +from, to: +to }
}),
}
}
const part1 = (rawInput: string) => {
const { stacks, instructions } = parseInput(rawInput)
for (const { count, from, to } of instructions) {
for (let c = 0; c < count; c++) {
stacks[to].push(stacks[from].pop()!)
}
}
return stacks.map((stack) => stack.at(-1)).join('')
}
const part2 = (rawInput: string) => {
const { stacks, instructions } = parseInput(rawInput)
for (const { count, from, to } of instructions) {
stacks[to].push(...stacks[from].splice(stacks[from].length - count, count))
}
return stacks.map((stack) => stack.at(-1)).join('')
}
run({
part1: {
tests: [
{
input: ` [D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2`,
expected: 'CMZ',
},
],
solution: part1,
},
part2: {
tests: [
{
input: ` [D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2`,
expected: 'MCD',
},
],
solution: part2,
},
trimTestInputs: false,
// onlyTests: true,
})