-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
101 lines (83 loc) · 2.19 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { RADIX, sum } from '../../../utils/math.ts';
const BASE = 1000;
type Command = 'turn on' | 'turn off' | 'toggle';
interface Position {
x: number;
y: number;
}
interface Instruction {
command: Command;
start: Position;
end: Position;
}
function getIndex(x: number, y: number): number {
return BASE * x + y;
}
function parseInstruction(instruction: string): Instruction {
const { groups } = instruction.match(
/(?<command>turn on|turn off|toggle) (?<x1>\d+),(?<y1>\d+) through (?<x2>\d+),(?<y2>\d+)/,
);
const { command, x1, x2, y1, y2 } = groups;
return {
command,
start: {
x: parseInt(x1, RADIX),
y: parseInt(y1, RADIX),
},
end: {
x: parseInt(x2, RADIX),
y: parseInt(y2, RADIX),
},
};
}
function part1(instructions: string[]): number {
const grid = new Array(BASE ** 2).fill(false);
instructions.forEach((instruction) => {
const { command, start, end } = parseInstruction(instruction);
for (let { x } = start; x <= end.x; x += 1) {
for (let { y } = start; y <= end.y; y += 1) {
const index = getIndex(x, y);
switch (command) {
case 'turn on':
grid[index] = true;
break;
case 'turn off':
grid[index] = false;
break;
case 'toggle':
grid[index] = !grid[index];
break;
default:
break;
}
}
}
});
return grid.filter(Boolean).length;
}
function part2(instructions: string[]): number {
const grid = new Array(BASE ** 2).fill(0);
instructions.forEach((instruction) => {
const { command, start, end } = parseInstruction(instruction);
for (let { x } = start; x <= end.x; x += 1) {
for (let { y } = start; y <= end.y; y += 1) {
const index = getIndex(x, y);
switch (command) {
case 'turn on':
grid[index] += 1;
break;
case 'turn off':
grid[index] = Math.max(grid[index] - 1, 0);
break;
case 'toggle':
grid[index] += 2;
break;
default:
break;
}
}
}
});
return sum(grid);
}
export { part1, part2 };