Skip to content

Commit

Permalink
feat(js): add solutions for 2024 day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
timkurvers committed Dec 2, 2024
1 parent 627d1e6 commit 46106ec
Show file tree
Hide file tree
Showing 3 changed files with 1,053 additions and 0 deletions.
40 changes: 40 additions & 0 deletions js/src/2024/02/index.js
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;
});
13 changes: 13 additions & 0 deletions puzzles/2024/02/examples.yaml
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
Loading

0 comments on commit 46106ec

Please sign in to comment.