Skip to content

Commit

Permalink
Day 13
Browse files Browse the repository at this point in the history
  • Loading branch information
Av32000 committed Dec 13, 2024
1 parent 49c9441 commit 4c39caf
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
52 changes: 52 additions & 0 deletions 13/part1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString().trim();
const machines = [];

input.split("\n\n").forEach((m) => {
const regex = /X[+=](\d+).*?Y[+=](\d+)/g;
let match;
const results = [];
while ((match = regex.exec(m.trim())) !== null) {
results.push({ X: parseInt(match[1]), Y: parseInt(match[2]) });
}

machines.push({
id: machines.length,
buttonA: [results[0].X, results[0].Y],
buttonB: [results[1].X, results[1].Y],
prize: [results[2].X, results[2].Y],
result: null,
});
});

function solveEquationSystem(machine) {
let a = machine.buttonA[0];
let b = machine.buttonB[0];
let c = machine.buttonA[1];
let d = machine.buttonB[1];
let m1 = machine.prize[0];
let m2 = machine.prize[1];

let y = (a * m2 - c * m1) / (-c * b + d * a);
let x = (m1 - b * y) / a;

if (
Number.isInteger(y) &&
y >= 0 &&
y <= 100 &&
Number.isInteger(x) &&
x >= 0 &&
x <= 100
)
machine.result = [x, y];
}

let result = 0;
machines.forEach((m) => {
solveEquationSystem(m);
if (m.result) result += m.result[0] * 3 + m.result[1];
});

console.log(result);
45 changes: 45 additions & 0 deletions 13/part2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString().trim();
const machines = [];

input.split("\n\n").forEach((m) => {
const regex = /X[+=](\d+).*?Y[+=](\d+)/g;
let match;
const results = [];
while ((match = regex.exec(m.trim())) !== null) {
results.push({ X: parseInt(match[1]), Y: parseInt(match[2]) });
}

machines.push({
id: machines.length,
buttonA: [results[0].X, results[0].Y],
buttonB: [results[1].X, results[1].Y],
prize: [results[2].X + 10000000000000, results[2].Y + 10000000000000],
result: null,
});
});

function solveEquationSystem(machine) {
let a = machine.buttonA[0];
let b = machine.buttonB[0];
let c = machine.buttonA[1];
let d = machine.buttonB[1];
let m1 = machine.prize[0];
let m2 = machine.prize[1];

let y = (a * m2 - c * m1) / (-c * b + d * a);
let x = (m1 - b * y) / a;

if (Number.isInteger(y) && y >= 0 && Number.isInteger(x) && x >= 0)
machine.result = [x, y];
}

let result = 0;
machines.forEach((m) => {
solveEquationSystem(m);
if (m.result) result += m.result[0] * 3 + m.result[1];
});

console.log(result);

0 comments on commit 4c39caf

Please sign in to comment.