From 959cb8fd586a60bbcdb09ec730971df713ae0087 Mon Sep 17 00:00:00 2001 From: Joe Hildebrand Date: Thu, 5 Dec 2024 00:27:18 -0800 Subject: [PATCH] Day 5 --- day5.peggy | 10 ++++++++++ day5.ts | 36 ++++++++++++++++++++++++++++++++++++ inputs | 2 +- test/day5.js | 1 + 4 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 day5.peggy create mode 100644 day5.ts create mode 100644 test/day5.js diff --git a/day5.peggy b/day5.peggy new file mode 100644 index 0000000..9301963 --- /dev/null +++ b/day5.peggy @@ -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]+ diff --git a/day5.ts b/day5.ts new file mode 100644 index 0000000..15473a1 --- /dev/null +++ b/day5.ts @@ -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(args); + const order = new Set(); + 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)]; +} diff --git a/inputs b/inputs index f9def56..545dfbe 160000 --- a/inputs +++ b/inputs @@ -1 +1 @@ -Subproject commit f9def56e294696296806761bc751e9cddc7a79be +Subproject commit 545dfbe8c1614e19ca6e08fe010b399ffaa355d0 diff --git a/test/day5.js b/test/day5.js new file mode 100644 index 0000000..c013dd8 --- /dev/null +++ b/test/day5.js @@ -0,0 +1 @@ +export default [4662, 5900];