-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday13.ts
72 lines (61 loc) · 1.46 KB
/
day13.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
import type { Day } from './Day.ts';
interface Button {
x: number;
y: number;
cost: 1 | 3;
}
interface Block {
a: Button;
b: Button;
prize: {
x: number;
y: number;
};
}
export class DayImpl implements Day {
private readonly input: Block[];
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
return input
.trim()
.split('\n\n')
.map((block: string) => {
const [a, b, prize] = block.split('\n').map(line => line.match(/\d+/g)!.map(Number));
return {
a: { x: a[0], y: a[1], cost: 3 },
b: { x: b[0], y: b[1], cost: 1 },
prize: { x: prize[0], y: prize[1] },
} as Block;
});
}
partOne() {
return getNumTokens(this.input);
}
partTwo() {
const OFFSET = 10000000000000;
const withOffset: Block[] = this.input.map(({ a, b, prize }) => {
return {
a,
b,
prize: { x: prize.x + OFFSET, y: prize.y + OFFSET },
};
});
return getNumTokens(withOffset);
}
}
function getNumTokens(grid: Block[]) {
let tokens = 0;
for (const { a, b, prize } of grid) {
const d = a.x * b.y - a.y * b.x;
const A = (prize.x * b.y - prize.y * b.x) / d;
const B = (a.x * prize.y - a.y * prize.x) / d;
if (d === 0)
continue;
if (Number.isInteger(A) && Number.isInteger(B) && A >= 0 && B >= 0) {
tokens += A * a.cost + B * b.cost;
}
}
return tokens;
}