Day 19 part 2
This commit is contained in:
parent
6dba16a6fd
commit
7f8a4ebb89
1 changed files with 10 additions and 5 deletions
|
@ -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) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue