-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(js): add solutions for 2023 day 9
- Loading branch information
1 parent
6fc43c4
commit 1a7b6b6
Showing
3 changed files
with
257 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Oops, something went wrong.