56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
const fs = require('fs');
|
|
|
|
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
|
|
|
|
const lines = input.split("\n");
|
|
|
|
interface Coord { x: number, y: number };
|
|
|
|
interface equation {
|
|
prize: Coord,
|
|
a: Coord,
|
|
b: Coord,
|
|
}
|
|
|
|
const equations: Array<equation> = [];
|
|
|
|
for (let i = 0; i < lines.length; i += 4) {
|
|
let match = lines[i].match(/Button A: X\+(\d+), Y\+(\d+)/);
|
|
const a = { x: parseInt(match[1]), y: parseInt(match[2]) };
|
|
match = lines[i + 1].match(/Button B: X\+(\d+), Y\+(\d+)/);
|
|
const b = { x: parseInt(match[1]), y: parseInt(match[2]) };
|
|
match = lines[i + 2].match(/Prize: X=(\d+), Y=(\d+)/);
|
|
const prize = { x: parseInt(match[1]), y: parseInt(match[2]) };
|
|
// Part 2
|
|
prize.x += 10000000000000;
|
|
prize.y += 10000000000000;
|
|
|
|
equations.push({ prize, a, b });
|
|
}
|
|
|
|
let result = 0;
|
|
|
|
equations.forEach(({ a, b, prize }) => {
|
|
// x*94 + y*22 = 8400
|
|
// x*34 + y*67 = 5400
|
|
// x = (8400 - y*22)/94
|
|
// ((8400 - y*22)/94)*34 + y*67 = 5400
|
|
// (8400 - y*22) + ((y*67*94)/34) = 5400 * 94/34
|
|
// ((y*67*94)/34) - y*22 = ((5400 * 94/34)/34) - 8400
|
|
// y * (((67*94)/34) - 22) = ((5400 * 94)/34) - 8400
|
|
// y = (((5400 * 94)/34) - 8400) / (((67*94)/34) - 22)
|
|
|
|
const bPresses = (((prize.y * a.x) / a.y) - prize.x) / (((b.y * a.x) / a.y) - b.x);
|
|
const aPresses = (prize.x - (bPresses * b.x)) / a.x;
|
|
|
|
if (
|
|
Math.abs(bPresses - Math.round(bPresses)) < 0.001
|
|
&& Math.abs(aPresses - Math.round(aPresses)) < 0.001
|
|
&& aPresses > 0 && bPresses > 0
|
|
) {
|
|
result += (Math.round(aPresses) * 3) + Math.round(bPresses);
|
|
}
|
|
});
|
|
|
|
console.log(result);
|