From b42f579fbb6ad67b5afe9fd22916e6a5e215ad09 Mon Sep 17 00:00:00 2001 From: Tyler Beckman Date: Wed, 18 Dec 2024 23:17:56 -0700 Subject: [PATCH] Day 19 in TS again b/c why not and simple --- day19/part1.ts | 26 ++++++++++++++++++++++++++ day19/part2.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 day19/part1.ts create mode 100644 day19/part2.ts diff --git a/day19/part1.ts b/day19/part1.ts new file mode 100644 index 0000000..d3cc4c1 --- /dev/null +++ b/day19/part1.ts @@ -0,0 +1,26 @@ +function attempt(towels: string[], pattern: string): boolean { + if (pattern == "") return true; + let anySucceeded = false; + for (const towel of towels) { + if (pattern.startsWith(towel)) { + anySucceeded = anySucceeded || attempt(towels, pattern.substring(towel.length)); + } + } + return anySucceeded; +} + +export async function solve() { + const [towels, patterns] = await Deno.readTextFile( + import.meta.dirname + "/input.txt", + ).then( + (c) => [c.split("\n\n")[0].trim().split(", "), c.split("\n\n")[1].trim().split("\n")] + ); + towels.sort((a, b) => b.length - a.length); + + let sum = 0; + for (const pattern of patterns) { + if (attempt(towels, pattern)) sum++; + } + + return sum +} diff --git a/day19/part2.ts b/day19/part2.ts new file mode 100644 index 0000000..3cb8693 --- /dev/null +++ b/day19/part2.ts @@ -0,0 +1,28 @@ +const cache: Record = {}; + +function attempt(towels: string[], pattern: string): number { + if (pattern.length <= 0) return 1; + if (pattern in cache) return cache[pattern]; + + const val = towels + .filter(t => pattern.startsWith(t)) + .map(t => attempt(towels, pattern.substring(t.length))) + .reduce((acc, cur) => acc + cur, 0); + cache[pattern] = val; + return val; +} + +export async function solve() { + const [towels, patterns] = await Deno.readTextFile( + import.meta.dirname + "/input.txt", + ).then( + (c) => [c.split("\n\n")[0].trim().split(", "), c.split("\n\n")[1].trim().split("\n")] + ); + + let sum = 0; + for (const pattern of patterns) { + sum += attempt(towels, pattern); + } + + return sum +}