From 47b73978071487b1e3de0ff9b058d99be0ea1876 Mon Sep 17 00:00:00 2001 From: letelete Date: Fri, 20 Dec 2024 10:20:13 +0100 Subject: [PATCH] =?UTF-8?q?Add=20day=2019=20of=20year=202024=20?= =?UTF-8?q?=F0=9F=A5=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2024/days/day-19/README.md | 21 ++++++++++++++ 2024/days/day-19/in.sample.txt | 10 +++++++ 2024/days/day-19/main.js | 52 ++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 2024/days/day-19/README.md create mode 100644 2024/days/day-19/in.sample.txt create mode 100644 2024/days/day-19/main.js 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 };