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 +}