-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.ts
68 lines (58 loc) · 1.78 KB
/
13.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
import { getInput, reduceSum } from "./common";
const input = await getInput(13);
type Coord = { x: number; y: number };
type Machine = { a: Coord, b: Coord, prize: Coord };
type Pushes = { a: number, b: number };
const machines = input
.split("\n\n")
.map(machine => {
const [a, b, prize] = machine.split("\n");
const regex = /X(?:\+|=)(\d+), Y(?:\+|=)(\d+)/;
const aMatch = a.match(regex);
const bMatch = b.match(regex);
const prizeMatch = prize.match(regex);
if (!aMatch || !bMatch || !prizeMatch) {
throw new Error("Invalid machine");
}
return <Machine>{
a: { x: parseInt(aMatch[1]), y: parseInt(aMatch[2]) },
b: { x: parseInt(bMatch[1]), y: parseInt(bMatch[2]) },
prize: { x: parseInt(prizeMatch[1]), y: parseInt(prizeMatch[2]) }
};
});
const getAPushes = (machine: Machine) =>
(machine.prize.y * machine.b.x - machine.b.y * machine.prize.x) /
(machine.b.x * machine.a.y - machine.b.y * machine.a.x);
const getSolution = (machine: Machine): Pushes | false => {
const aPushes = getAPushes(machine);
if (Math.round(aPushes) !== aPushes) {
return false;
}
const bPushes = (machine.prize.x - aPushes * machine.a.x) / machine.b.x;
if (Math.round(bPushes) !== bPushes) {
return false;
}
return { a: aPushes, b: bPushes };
}
// Part 1
console.log(
machines
.map(getSolution)
.filter(solution => !!solution)
.map(solution => solution.a * 3 + solution.b)
.reduce(reduceSum)
);
// Part 2
const tuneMachine = (machine: Machine) => {
machine.prize.x += 10000000000000;
machine.prize.y += 10000000000000;
return machine;
}
console.log(
machines
.map(tuneMachine)
.map(getSolution)
.filter(solution => !!solution)
.map(solution => solution.a * 3 + solution.b)
.reduce(reduceSum)
);