Skip to content

Commit

Permalink
Day 10
Browse files Browse the repository at this point in the history
  • Loading branch information
hildjj committed Dec 10, 2024
1 parent 1093de7 commit 5f4583b
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 2 deletions.
6 changes: 6 additions & 0 deletions day10.peggy
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
lines = line+
line = @num+ "\n"

num
= n:$[0-9] { return parseInt(n, 10) }
/ '.' { return -1 }
57 changes: 57 additions & 0 deletions day10.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Point, PointSet, Rect } from './lib/rect.ts';
import { type MainArgs, parseFile } from './lib/utils.ts';

type Parsed = number[][];

function hike(r: Rect<number>, p: Point, next: number, peaks: PointSet): void {
for (const n of p.cardinal(r)) {
if (r.get(n) === next) {
if (next === 9) {
peaks.add(n);
} else {
hike(r, n, next + 1, peaks);
}
}
}
}

function hike2(r: Rect<number>, p: Point, next: number): number {
// I expected to have to memoize or work from the back to get a solution
// that worked fast enough.
let count = 0;
for (const n of p.cardinal(r)) {
if (r.get(n) === next) {
if (next === 9) {
count++;
} else {
count += hike2(r, n, next + 1);
}
}
}
return count;
}

function part1(inp: Parsed): number {
const r = new Rect(inp);
let tot = 0;
for (const p of r.filter(v => v === 0)) {
const peaks = new PointSet();
hike(r, p, 1, peaks);
tot += peaks.size;
}
return tot;
}

function part2(inp: Parsed): number {
const r = new Rect(inp);
let tot = 0;
for (const p of r.filter(v => v === 0)) {
tot += hike2(r, p, 1);
}
return tot;
}

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
2 changes: 1 addition & 1 deletion lib/rect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export class Point implements PointLike {
return (this.x === p.x) && (this.y === p.y);
}

cardinal(r?: Rect): Point[] {
cardinal<T>(r?: Rect<T>): Point[] {
const ret: Point[] = [];
for (const [dx, dy] of Point.CARDINAL) {
const p = this.xlate(dx, dy);
Expand Down

0 comments on commit 5f4583b

Please sign in to comment.