diff --git a/2024/13/2024-13.run.xml b/2024/13/2024-13.run.xml new file mode 100644 index 0000000..42d25a9 --- /dev/null +++ b/2024/13/2024-13.run.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/2024/13/index.test.ts b/2024/13/index.test.ts new file mode 100644 index 0000000..a5682f7 --- /dev/null +++ b/2024/13/index.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'bun:test'; +import { solveFirst, solveSecond } from './index.ts'; + +describe('2024-13', () => { + const testInput = `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`; + it('first', () => { + expect(solveFirst(testInput)).toBe(480); + }); + it('second', () => { + expect(solveSecond(testInput)).toBe(875318608908); + }); +}); diff --git a/2024/13/index.ts b/2024/13/index.ts new file mode 100644 index 0000000..c3ce065 --- /dev/null +++ b/2024/13/index.ts @@ -0,0 +1,33 @@ +import { sumArray } from '../../utils/array.ts'; +import { type Coordinate, isInteger } from '../../utils/coordinates.ts'; + +function findIntersection(input: string, offset: number = 0) { + const match = input.matchAll( + /^Button A: X\+(\d*), Y\+(\d*)\nButton B: X\+(\d*), Y\+(\d*)\nPrize: X=(\d*), Y=(\d*)$/gm + ); + + const matches = Array.from(match, (m) => ({ + a: [m[1], m[2]].map(Number), + b: [m[3], m[4]].map(Number), + price: [m[5], m[6]].map((n) => Number(n) + offset) + })); + + const intersection = matches + .map( + ({ a: [a1, a2], b: [b1, b2], price: [p1, p2] }) => + [ + (b1 * -p2 - b2 * -p1) / (a1 * b2 - a2 * b1), + (-p1 * a2 - -p2 * a1) / (a1 * b2 - a2 * b1) + ] as Coordinate + ) + .filter(isInteger); + + return sumArray(intersection.map(([a, b]) => 3 * a + b)); +} + +export function solveFirst(input: string): number { + return findIntersection(input); +} +export function solveSecond(input: string): number { + return findIntersection(input, 10000000000000); +} diff --git a/2024/13/run.ts b/2024/13/run.ts new file mode 100644 index 0000000..88783cd --- /dev/null +++ b/2024/13/run.ts @@ -0,0 +1,12 @@ +import { join } from 'path'; +import { solveFirst, solveSecond } from './index.ts'; + +const input = await Bun.file(join(__dirname, 'input.txt')).text(); + +const firstAnswer = solveFirst(input); + +console.log(firstAnswer); + +const secondAnswer = solveSecond(input); + +console.log(secondAnswer);