Day 6 & 7
This commit is contained in:
34
2024/07/index.ts
Normal file
34
2024/07/index.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
const fs = require('fs');
|
||||
|
||||
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
|
||||
|
||||
const equations: Array<string> = input.split("\n");
|
||||
|
||||
let sum = 0;
|
||||
|
||||
const operators = [(a: number, b: number) => a * b, (a: number, b: number) => a + b, /** Part 2 */ (a: number, b: number) => parseInt(''+a+b)];
|
||||
|
||||
function recurseSum(carry: number, remaining: Array<number>, target: number, sum: string = ''): boolean {
|
||||
if (!remaining.length) {
|
||||
return target === carry;
|
||||
}
|
||||
const nextNum = remaining[0];
|
||||
for (let o of operators) {
|
||||
const newResult = recurseSum(o(carry, nextNum), remaining.slice(1), target);
|
||||
if (newResult) {
|
||||
return newResult;
|
||||
}
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
equations.forEach((eq) => {
|
||||
const [testStr, numStr] = eq.split(':');
|
||||
const test = parseInt(testStr);
|
||||
const nums = numStr.trim().split(' ').map((n) => parseInt(n));
|
||||
if (recurseSum(nums[0], nums.slice(1), test)) {
|
||||
sum += test;
|
||||
}
|
||||
});
|
||||
|
||||
console.log(sum);
|
||||
Reference in New Issue
Block a user