Skip to content

Commit

Permalink
Day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
hildjj committed Dec 2, 2024
1 parent 17eb1cb commit f0880b8
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
4 changes: 4 additions & 0 deletions day2.peggy
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lines = (@num|.., _| "\n")*

num = n:$[0-9]+ { return parseInt(n, 10) }
_ = [ \t]+
52 changes: 52 additions & 0 deletions day2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { type MainArgs, parseFile } from './lib/utils.ts';

type Parsed = number[][];

function isSafe(levels: number[]): boolean {
if (levels.length < 2) {
return true;
}
let prev = levels[0];
const dir = Math.sign(prev - levels[1]);
for (let i = 1; i < levels.length; i++) {
const l = levels[i];
const diff = prev - l;
if ((diff === 0) || (Math.abs(diff) > 3) || (Math.sign(diff) !== dir)) {
return false;
}
prev = l;
}
return true;
}

function part1(inp: Parsed): number {
let count = 0;
for (const levels of inp) {
if (isSafe(levels)) {
count++;
}
}
return count;
}

function part2(inp: Parsed): number {
let count = 0;
for (const levels of inp) {
if (isSafe(levels)) {
count++;
} else {
for (let i=0; i < levels.length; i++) {
if (isSafe(levels.toSpliced(i, 1))) {
count++;
break;
}
}
}
}
return count;
}

export default async function main(args: MainArgs): Promise<[number, number]> {
const inp = await parseFile<Parsed>(args);
return [part1(inp), part2(inp)];
}
2 changes: 1 addition & 1 deletion inputs
1 change: 1 addition & 0 deletions test/day2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default [326, 381];

0 comments on commit f0880b8

Please sign in to comment.