-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.ts
118 lines (88 loc) · 2.43 KB
/
solution.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { answer, question, section } from "../utils.ts";
export default function solution(input: string) {
const lines = input.split("\n");
// Part 1
question("After the rearrangement procedure completes, what crate ends up on top of each stack?");
type Stack = Array<string>;
type Stacks = Array<Stack>
function getStacks(): Stacks {
const stacks: Array<Array<string>> = [];
for (const line of lines) {
if (line === "") continue;
if (line.startsWith("[") || line.startsWith(" ")) {
for (let i = 0; 1 + i * 4 < line.length; i++) {
const char = line[1 + i * 4];
if (/[A-Z]/.test(char)) {
if (!stacks[i]) {
stacks[i] = [];
}
const stack = stacks[i];
stack.unshift(char);
}
}
}
}
return stacks;
}
function moveCM9000(stacks: Stacks): Stacks {
for (const line of lines) {
if (line.startsWith("m")) {
const match = /move (\d+) from (\d+) to (\d+)/.exec(line);
if (!match) continue;
const amount = parseInt(match[1]);
const from = parseInt(match[2]) - 1;
const to = parseInt(match[3]) - 1;
for (let n = 0; n < amount; n++) {
const item = stacks[from].pop();
if (!item) continue;
stacks[to].push(item);
}
}
}
return stacks;
}
function getTops(stacks: Stacks): Array<string> {
const tops: Array<string> = [];
for (const stack of stacks) {
const top = stack[stack.length - 1];
if (top) {
tops.push(top);
} else {
tops.push("_");
}
}
return tops;
}
answer(getTops(moveCM9000(getStacks())).join(""));
// Part 2
question("After the rearrangement procedure completes, what crate ends up on top of each stack?");
function moveCM9001(stacks: Stacks): Stacks {
for (const line of lines) {
if (line.startsWith("m")) {
const match = /move (\d+) from (\d+) to (\d+)/.exec(line);
if (!match) continue;
const amount = parseInt(match[1]);
const from = parseInt(match[2]) - 1;
const to = parseInt(match[3]) - 1;
const items = stacks[from].splice(stacks[from].length - amount, amount);
stacks[to].push(...items);
}
}
return stacks;
}
answer(getTops(moveCM9001(getStacks())).join(""));
}
const example =
` [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`;
const input = await Deno.readTextFile("./input.txt");
section("Example");
solution(example);
section("Input");
solution(input);