Skip to content

Commit

Permalink
feat(js): add solutions for 2023 day 9
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 9, 2023
1 parent 6fc43c4 commit 1a7b6b6
Show file tree
Hide file tree
Showing 3 changed files with 257 additions and 0 deletions.
47 changes: 47 additions & 0 deletions js/src/2023/09/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { cast, solution, sum } from '../../utils';

const parse = (input) => (
input.trim().split('\n').map((line) => line.split(' ').map(cast))
);

const isZero = (value) => value === 0;

const derive = (sequence) => {
const lastIndex = sequence.length - 1;
return sequence.reduce((list, current, index) => {
const next = sequence.at(index + 1);
if (index !== lastIndex) {
list.push(next - current);
}
return list;
}, []);
};

const extend = (sequence, append = true) => {
let value = 0;
if (!sequence.every(isZero)) {
const derivation = derive(sequence);
const extended = extend(derivation, append);
value = append ? sequence.at(-1) + extended.at(-1) : sequence.at(0) - extended.at(0);
}

const next = [...sequence];
if (append) {
next.push(value);
} else {
next.unshift(value);
}
return next;
};

export const partOne = solution((input) => {
const sequences = parse(input);
const extended = sequences.map((seq) => extend(seq));
return sum(extended.map((sequence) => sequence.at(-1)));
});

export const partTwo = solution((input) => {
const sequences = parse(input);
const extended = sequences.map((seq) => extend(seq, false));
return sum(extended.map((sequence) => sequence.at(0)));
});
10 changes: 10 additions & 0 deletions puzzles/2023/09/examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
part-one:
- input: &example1 |
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
answer: 114

part-two:
- input: *example1
answer: 2
Loading

0 comments on commit 1a7b6b6

Please sign in to comment.