Day 19 part 2

This commit is contained in:
Sven Weidauer 2024-12-25 12:49:52 +01:00
parent 6dba16a6fd
commit 7f8a4ebb89

View file

@ -5,17 +5,22 @@ fun main() {
.flatMap { it.split(",\\s*".toRegex()) } .flatMap { it.split(",\\s*".toRegex()) }
.toList() .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") println("Part 1: $part1")
val part2 = patterns.sumOf { waysToMake(it, towels) }
println("Part 2: $part2")
} }
private val patternMemo = mutableMapOf<String, Boolean>() private val patternMemo = mutableMapOf<String, Long>()
fun isPossible(pattern: String, towels: List<String>): Boolean { fun waysToMake(pattern: String, towels: List<String>): Long {
if (pattern.isEmpty()) return true if (pattern.isEmpty()) return 1
return patternMemo.getOrPut(pattern) { return patternMemo.getOrPut(pattern) {
towels towels
.filter { pattern.startsWith(it) } .filter { pattern.startsWith(it) }
.any { isPossible(pattern.substring(it.length), towels) } .fold(0) { acc, towel -> acc + waysToMake(pattern.substring(towel.length), towels) }
} }
} }