Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 9, 2023
1 parent dc3367d commit 4ee08bd
Showing 1 changed file with 19 additions and 21 deletions.
40 changes: 19 additions & 21 deletions src/2023/day09.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
function calcHistory(sequence) {
const history = [sequence];
let differences = sequence;
while (differences.some(x => x !== 0)) {
differences = differences.reduce(
(acc, curr, i) => (i === 0 ? [] : [...acc, curr - differences[i - 1]]),
[],
);
history.push(differences);
}
return history;
function solve(input, fn) {
const sequences = input.split('\n').map(line => line.split(' ').map(Number));
const histories = sequences.map(sequence => {
const history = [sequence];
let differences = sequence;
while (differences.some(x => x !== 0)) {
differences = differences.reduce(
(acc, curr, i, arr) => (i === 0 ? acc : acc.concat(curr - arr[i - 1])),
[],
);
history.push(differences);
}
return history;
});
return histories.map(fn).reduce((a, b) => a + b);
}

function getNextNumber(history) {
Expand All @@ -20,21 +24,15 @@ function getNextNumber(history) {

function getPrevNumber(history) {
for (let i = history.length - 2; i >= 0; i--) {
history[i].unshift(history[i][0] - history[i + 1][0]);
history[i].unshift(history[i].at(0) - history[i + 1].at(0));
}
return history[0][0];
return history[0].at(0);
}

export function part1(input) {
const sequences = input.split('\n').map(line => line.split(' ').map(Number));
const histories = sequences.map(calcHistory);
const next = histories.map(getNextNumber);
return next.reduce((a, b) => a + b);
return solve(input, getNextNumber);
}

export function part2(input) {
const sequences = input.split('\n').map(line => line.split(' ').map(Number));
const histories = sequences.map(calcHistory);
const next = histories.map(getPrevNumber);
return next.reduce((a, b) => a + b);
return solve(input, getPrevNumber);
}

0 comments on commit 4ee08bd

Please sign in to comment.