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[diff.length - 1]); } function getNextFactors(factors: number[]){ const ret = []; let cur = 0; for (let i = factors.length - 1; i >= 0; i--){ cur += factors[i]; ret.push(cur); } return ret.reverse(); } console.log(calcFactor([10, 13, 16 , 21, 30, 45])); console.log(getNextFactors(calcFactor([10, 13, 16 , 21, 30, 45]))) let factorsArr = numbers.map(series => { return calcFactor(series); }); factorsArr = factorsArr.map(getNextFactors); console.log(factorsArr.map(x=> x[0]).reduce((a, b) => a + b, 0));