Skip to content

Commit 1355f0c

Browse files
committed
19
1 parent 5075998 commit 1355f0c

File tree

4 files changed

+470
-0
lines changed

4 files changed

+470
-0
lines changed

src/main/kotlin/19.kt

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
fun main() {
2+
println(solve19a(readInputLines("19")))
3+
println(solve19b(readInputLines("19")))
4+
}
5+
6+
fun solve19a(lines: List<String>): Int {
7+
val (designs, towels) = parseInput(lines)
8+
return towels.count { countPossibleOrders(designs, it) > 0 }
9+
}
10+
11+
fun solve19b(lines: List<String>): Long {
12+
val (designs, towels) = parseInput(lines)
13+
return towels.sumOf { countPossibleOrders(designs, it) }
14+
}
15+
16+
private data class Input19(val designs: List<String>, val towels: List<String>)
17+
18+
private fun parseInput(lines: List<String>): Input19 {
19+
val designs = lines[0].split(", ")
20+
val towels = lines.drop(2)
21+
return Input19(designs, towels)
22+
}
23+
24+
private val MEM = mutableMapOf<String, Long>()
25+
private fun countPossibleOrders(designs: List<String>, towels: String): Long {
26+
if (towels.isEmpty()) {
27+
return 1
28+
}
29+
if (towels !in MEM) {
30+
var result = 0L
31+
for (d in designs) {
32+
if (towels.startsWith(d)) {
33+
result += countPossibleOrders(designs, towels.removePrefix(d))
34+
}
35+
}
36+
MEM[towels] = result
37+
}
38+
39+
return checkNotNull(MEM[towels])
40+
}

0 commit comments

Comments
 (0)