-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
executable file
·84 lines (67 loc) · 2.07 KB
/
main.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
#!/usr/bin/env deno run --allow-read
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import { addCoords, Coord, ensureElementOf } from "../../2020/utils.ts";
const directions = ["forward", "down", "up"] as const;
type Direction = typeof directions[number];
type Step = { direction: Direction; amount: number };
const parseInput = (
string: string,
): Step[] =>
string.trim().split(/\n\W*/).map((line) => {
const [directionString, amountString] = line.split(" ");
return {
direction: ensureElementOf(directionString, directions),
amount: parseInt(amountString, 10),
};
});
const text = await Deno.readTextFile("input.txt");
const entries = parseInput(text);
const part1 = (steps: Step[]): number => {
const [position, depth] = steps.map(({ direction, amount }): Coord => {
switch (direction) {
case "forward":
return [amount, 0];
case "down":
return [0, amount];
case "up":
return [0, -amount];
}
}).reduce(addCoords);
return position * depth;
};
const example = parseInput(`
forward 5
down 5
forward 8
up 3
down 8
forward 2
`);
assertEquals(part1(example), 150, "Example is wrong!");
console.log("Result part 1: " + part1(entries));
type State = { aim: number; position: number; depth: number };
const part2 = (steps: Step[]): number => {
const initialState: State = { aim: 0, position: 0, depth: 0 };
const result = steps.reduce(
(prev: State, { direction, amount }): State => {
const { aim, position, depth } = prev;
switch (direction) {
case "forward":
return {
...prev,
position: position + amount,
depth: depth + aim * amount,
};
case "down":
return { ...prev, aim: aim + amount };
case "up":
return { ...prev, aim: aim - amount };
}
},
initialState,
);
const { position, depth } = result;
return position * depth;
};
assertEquals(part2(example), 900, "Example is wrong!");
console.log("Result part 2: " + part2(entries));