-
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 2024 day 2
- Loading branch information
1 parent
627d1e6
commit 46106ec
Showing
3 changed files
with
1,053 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,40 @@ | ||
import { solution } from '../../utils/index.js'; | ||
|
||
const parse = (input) => | ||
input | ||
.trim() | ||
.split('\n') | ||
.map((line) => line.split(' ').map(Number)); | ||
|
||
const isSafe = (report) => { | ||
let sign; | ||
for (let i = 0; i < report.length - 1; ++i) { | ||
const current = report[i]; | ||
const next = report[i + 1]; | ||
|
||
const diff = current - next; | ||
const diffabs = Math.abs(diff); | ||
if (diff === 0) return false; | ||
if (diffabs < 1 || diffabs > 3) return false; | ||
|
||
const diffsign = Math.sign(diff); | ||
if (sign && diffsign !== sign) return false; | ||
sign = diffsign; | ||
} | ||
return true; | ||
}; | ||
|
||
const isSafeWithRemoval = (report) => { | ||
const variations = report.map((level, index) => report.slice(0, index).concat(report.slice(index + 1))); | ||
return variations.some(isSafe); | ||
}; | ||
|
||
export const partOne = solution((input) => { | ||
const reports = parse(input); | ||
return reports.filter(isSafe).length; | ||
}); | ||
|
||
export const partTwo = solution((input) => { | ||
const reports = parse(input); | ||
return reports.filter(isSafeWithRemoval).length; | ||
}); |
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,13 @@ | ||
part-one: | ||
- input: &example1 | | ||
7 6 4 2 1 | ||
1 2 7 8 9 | ||
9 7 6 2 1 | ||
1 3 2 4 5 | ||
8 6 4 4 1 | ||
1 3 6 7 9 | ||
answer: 2 | ||
|
||
part-two: | ||
- input: *example1 | ||
answer: 4 |
Oops, something went wrong.