This repository has been archived by the owner on Mar 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
78 lines (63 loc) · 2.22 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
import { toNumber } from 'lodash';
import AdventCommand from '~shared/advent-command';
import { parseFile, splitLines } from '~shared/file';
import { Point } from '~shared/point';
type Line = {
from: Point;
to: Point;
};
type Input = Line[];
export default class Day5Challenge extends AdventCommand<Input> {
static aliases = ['day:5'];
protected async parseInput(test: boolean): Promise<Input> {
const data = await parseFile(test ? 'testinput' : 'input', __dirname);
return splitLines(data).map((line) => {
const [from, to] = line.split(' -> ');
const [fromX, fromY] = from.split(',').map(toNumber);
const [toX, toY] = to.split(',').map(toNumber);
return {
from: { x: fromX, y: fromY },
to: { x: toX, y: toY }
} as Line;
});
}
private makeGrid(input: Input): number[][] {
let maxX = 0;
let maxY = 0;
for (const line of input) {
maxX = Math.max(maxX, line.from.x, line.to.x);
maxY = Math.max(maxY, line.from.y, line.to.y);
}
const grid: number[][] = [];
for (let y = 0; y <= maxY; y++) {
grid[y] = [];
for (let x = 0; x <= maxX; x++) {
grid[y][x] = 0;
}
}
return grid;
}
protected part1(input: Input): number {
return this.part2(input.filter((line) => line.from.x === line.to.x || line.from.y === line.to.y));
}
protected part2(input: Input): number {
const grid = this.makeGrid(input);
for (const line of input) {
const dir: Point = {
x: line.from.x === line.to.x ? 0 : line.from.x < line.to.x ? 1 : -1,
y: line.from.y === line.to.y ? 0 : line.from.y < line.to.y ? 1 : -1
};
const curr: Point = {
x: line.from.x,
y: line.from.y
};
grid[curr.y][curr.x]++;
while (curr.x !== line.to.x || curr.y !== line.to.y) {
curr.x += dir.x;
curr.y += dir.y;
grid[curr.y][curr.x]++;
}
}
return grid.flat().filter((i) => i > 1).length;
}
}