Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day 5 #16

Merged
merged 1 commit into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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];
Loading