Day 13
prelude
https://adventofcode.com/2024/day/13
import { inputDay, munge } from "./lib/utilities.js"
const parser = inp =>
inp
.replaceAll(/[+=]/g, " ")
.split("\n\n")
.map(munge)
.map(t => [t[0][3], t[0][5], t[1][3], t[1][5], t[2][2], t[2][4]])
const test = parser(`Button A: X+94, Y+34
Button B: X+22, Y+67
Prize: X=8400, Y=5400
Button A: X+26, Y+66
Button B: X+67, Y+21
Prize: X=12748, Y=12176
Button A: X+17, Y+86
Button B: X+84, Y+37
Prize: X=7870, Y=6450
Button A: X+69, Y+23
Button B: X+27, Y+71
Prize: X=18641, Y=10279
`)
display(test)
const input = await inputDay(13, { parser })
part 1
Our goal is to minimize
That's 2 unknowns (
Now we can substitute that into the second equation and solve for
Let's see if it works!
The only change I made from directly implementing the equation above is to check for non-integral results, and return [0, 0] in that case; that makes it easier for us to sum up the results later on.
function intersect(x1, y1, x2, y2, x, y) {
if ((x1 * y - x * y1) % (x1 * y2 - x2 * y1) !== 0) return [0, 0]
const b = (x1 * y - x * y1) / (x1 * y2 - x2 * y1)
if ((x - b * x2) % x1 !== 0) return [0, 0]
const a = (x - b * x2) / x1
return [a, b]
}
display(intersect(94, 34, 22, 67, 8400, 5400))
Woo, it seems like it. Now we can sum up the intersections in the way specified by the problem, and we're done
function total(testcases) {
return testcases
.map(t => intersect.apply(null, t))
.reduce((acc, [a, b]) => acc + (3 * a + b), 0)
}
display(total(test))
display(total(input))
part 2
Let's find out if our javascript integers overflow:
display(
total(
input.map(t => [
t[0],
t[1],
t[2],
t[3],
10000000000000 + t[4],
10000000000000 + t[5],
]),
),
)
Since my submitted answer was correct, it seems like they don't, so we don't need to rewrite our functions in terms of BigInts.