diff --git a/2024/days/day-19/README.md b/2024/days/day-19/README.md new file mode 100644 index 0000000..ea1b1be --- /dev/null +++ b/2024/days/day-19/README.md @@ -0,0 +1,21 @@ +# Benchmark + +``` +Platform: darwin arm64 +CPU: Apple M3 Pro 11 Cores +Memory: 18.00 GB +``` + +## Sample 1 + +| part | time (~) | μs | +| ---- | -------- | ------------------- | +| 1 | 0.16ms | 0.1602500000000049 | +| 2 | 0.03ms | 0.03212500000000773 | + +## Answer + +| part | time (~) | μs | +| ---- | -------- | --------- | +| 1 | 74.96ms | 74.959875 | +| 2 | 51.48ms | 51.477959 | diff --git a/2024/days/day-19/in.sample.txt b/2024/days/day-19/in.sample.txt new file mode 100644 index 0000000..29648be --- /dev/null +++ b/2024/days/day-19/in.sample.txt @@ -0,0 +1,10 @@ +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb diff --git a/2024/days/day-19/main.js b/2024/days/day-19/main.js new file mode 100644 index 0000000..a7af528 --- /dev/null +++ b/2024/days/day-19/main.js @@ -0,0 +1,52 @@ +function parse(source) { + const [patterns, designs] = source + .trim() + .split('\n\n') + .map((e) => e.match(/(\w+)/g)); + + return { patterns, designs }; +} + +function createPatternsCounter(patterns) { + const memo = new Map(); + + return (design) => { + const count = (str) => { + if (!str.length) { + return 1; + } + + if (memo.has(str)) { + return memo.get(str); + } + + let localCount = 0; + for (const pattern of patterns) { + if (str.startsWith(pattern)) { + const substr = str.slice(pattern.length); + localCount += count(substr); + } + } + + memo.set(str, localCount); + + return localCount; + }; + + return count(design); + }; +} + +function part1(data) { + const countWaysToCreateDesign = createPatternsCounter(data.patterns); + return data.designs.filter(countWaysToCreateDesign).length; +} + +function part2(data) { + const countWaysToCreateDesign = createPatternsCounter(data.patterns); + return data.designs + .map(countWaysToCreateDesign) + .reduce((sum, e) => sum + e, 0); +} + +module.exports = { parse, part1, part2 };