From 6f895c334103e4279af32062ff359aec944f120a Mon Sep 17 00:00:00 2001 From: Tim Kurvers Date: Sat, 21 Dec 2024 19:00:35 +0100 Subject: [PATCH] feat(js): add solutions for 2024 day 19 --- js/src/2024/19/index.js | 48 +++++++++++++++++++++++++++++++++++ puzzles/2024/19/examples.yaml | 17 +++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 js/src/2024/19/index.js create mode 100644 puzzles/2024/19/examples.yaml diff --git a/js/src/2024/19/index.js b/js/src/2024/19/index.js new file mode 100644 index 0000000..861ac38 --- /dev/null +++ b/js/src/2024/19/index.js @@ -0,0 +1,48 @@ +import { solution } from '../../utils/index.js'; + +const parse = (input) => { + const parts = input.trim().split('\n\n'); + + const available = parts[0].split(', '); + const desired = parts[1].split('\n'); + + return { available, desired }; +}; + +// Calculates whether a given design is possible and returns how many variations +const build = (design, available, cache = new Map()) => { + if (cache.has(design)) { + return cache.get(design); + } + + let count = 0; + for (const pattern of available) { + if (design.startsWith(pattern)) { + const remaining = design.slice(pattern.length); + + if (!remaining.length) { + count += 1; + continue; + } + + count += build(remaining, available, cache); + } + } + cache.set(design, count); + return count; +}; + +export const partOne = solution((input) => { + const { available, desired } = parse(input); + return desired.reduce((sum, design) => { + if (build(design, available)) { + return sum + 1; + } + return sum; + }, 0); +}); + +export const partTwo = solution((input) => { + const { available, desired } = parse(input); + return desired.reduce((sum, design) => sum + build(design, available), 0); +}); diff --git a/puzzles/2024/19/examples.yaml b/puzzles/2024/19/examples.yaml new file mode 100644 index 0000000..abedfdd --- /dev/null +++ b/puzzles/2024/19/examples.yaml @@ -0,0 +1,17 @@ +part-one: + - input: &example1 | + r, wr, b, g, bwu, rb, gb, br + + brwrr + bggr + gbbr + rrbgbr + ubwu + bwurrg + brgr + bbrgwb + answer: 6 + +part-two: + - input: *example1 + answer: 16