aoc-2023/day_9/solve_2.ts

45 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

2024-12-09 22:41:02 +09:00
const input = await Deno.readTextFile("input.txt");
const lines = input.split("\n").map(x => x.trim()).filter(x => x.length > 0);
const numbers = lines.map(x => x.split(" ").map(x => parseInt(x)));
function calcDiff(series: number[]){
return series.map((x, i) => {
if (i === series.length - 1){
return 0;
}
return series[i + 1] - x;
}).slice(0, -1);
}
function calcFactor(series: number[]){
const diffs = [series] as number[][];
for (let i = 0; i < series.length - 1; i++){
const diff = calcDiff(diffs[diffs.length - 1]);
diffs.push(diff);
if (diff.every(x => x === 0)){
break;
}
}
return diffs.map(diff => diff[0]);
}
function getPrevFactors(factors: number[]){
const ret = [];
let cur = 0;
for (let i = factors.length - 1; i >= 0; i--){
cur = factors[i] - cur;
ret.push(cur);
}
return ret.reverse();
}
console.log(calcFactor([10, 13, 16 , 21, 30, 45]));
console.log(getPrevFactors(calcFactor([10, 13, 16 , 21, 30, 45])))
let factorsArr = numbers.map(series => {
return calcFactor(series);
});
factorsArr = factorsArr.map(getPrevFactors);
console.log(factorsArr.map(x=> x[0]).reduce((a, b) => a + b, 0));