From 7f8a4ebb896336ba1308aec23d67d062c07dcfd4 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Wed, 25 Dec 2024 12:49:52 +0100 Subject: [PATCH] Day 19 part 2 --- 2024/src/main/kotlin/day19.kt | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/2024/src/main/kotlin/day19.kt b/2024/src/main/kotlin/day19.kt index b95c49c..ae16405 100644 --- a/2024/src/main/kotlin/day19.kt +++ b/2024/src/main/kotlin/day19.kt @@ -5,17 +5,22 @@ fun main() { .flatMap { it.split(",\\s*".toRegex()) } .toList() - val part1 = Sequence { iterator }.count { isPossible(it, towels) } + val patterns = Sequence { iterator }.toList() + + val part1 = patterns.count { waysToMake(it, towels) > 0 } println("Part 1: $part1") + + val part2 = patterns.sumOf { waysToMake(it, towels) } + println("Part 2: $part2") } -private val patternMemo = mutableMapOf() +private val patternMemo = mutableMapOf() -fun isPossible(pattern: String, towels: List): Boolean { - if (pattern.isEmpty()) return true +fun waysToMake(pattern: String, towels: List): Long { + if (pattern.isEmpty()) return 1 return patternMemo.getOrPut(pattern) { towels .filter { pattern.startsWith(it) } - .any { isPossible(pattern.substring(it.length), towels) } + .fold(0) { acc, towel -> acc + waysToMake(pattern.substring(towel.length), towels) } } }