Skip to content

Commit

Permalink
Merge pull request #16 from hildjj/day5
Browse files Browse the repository at this point in the history
Day 5
  • Loading branch information
hildjj authored Dec 7, 2024
2 parents 511e4a2 + 959cb8f commit 276ef4f
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
10 changes: 10 additions & 0 deletions day5.peggy
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
manual = @order "\n" @pages

order = (@num "|" @num "\n")*

pages = (@page "\n")+

page = num|1.., ","|

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

type Parsed = [[number, number][], number[][]];

function part1(inp: number[][][]): number {
return inp
.filter(([before, after]) => before.join(',') === after.join(','))
.reduce((t, [before]) => t + before[Math.floor(before.length / 2)], 0);
}

function part2(inp: number[][][]): number {
return inp
.filter(([before, after]) => before.join(',') !== after.join(','))
.reduce((t, [_, after]) => t + after[Math.floor(after.length / 2)], 0);
}

export default async function main(args: MainArgs): Promise<[number, number]> {
const inp = await parseFile<Parsed>(args);
const order = new Set<string>();
for (const [x, y] of inp[0]) {
order.add(`${x},${y}`);
}
const beforeAndAfter = inp[1].map((pages) => {
const sorted = [...pages].sort((a, b) => {
if (order.has(`${a},${b}`)) {
return -1;
}
if (order.has(`${b},${a}`)) {
return 1;
}
return 0;
});
return [pages, sorted];
});
return [part1(beforeAndAfter), part2(beforeAndAfter)];
}
2 changes: 1 addition & 1 deletion inputs
1 change: 1 addition & 0 deletions test/day5.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default [4662, 5900];

0 comments on commit 276ef4f

Please sign in to comment.