Skip to content

Commit 3bc9f5d

Browse files
committed
Day 19
1 parent 66afa06 commit 3bc9f5d

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed

src/main/kotlin/y24/Day19.kt

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package y24
2+
3+
import common.puzzle.solvePuzzle
4+
import common.puzzle.Input
5+
import common.puzzle.Puzzle
6+
7+
8+
fun main() = solvePuzzle(year = 2024, day = 19) { Day19(it) }
9+
10+
class Day19(val input: Input) : Puzzle {
11+
private val patterns = input.lines[0].split(", ")
12+
private val designs = input.lines.subList(2, input.lines.size)
13+
14+
data class TrieNode(
15+
val c: Char,
16+
val children: MutableMap<Char, TrieNode> = mutableMapOf(),
17+
var pattern: String? = null,
18+
)
19+
20+
private fun buildTrie(patterns: List<String>): TrieNode {
21+
val root = TrieNode('-')
22+
patterns.forEach { pattern ->
23+
var node = root
24+
pattern.forEach { c ->
25+
node = node.children[c] ?: TrieNode(c).also { node.children[c] = it }
26+
}
27+
node.pattern = pattern
28+
}
29+
30+
return root
31+
}
32+
33+
private fun numPossibilities(design: String, trie: TrieNode, cache: MutableMap<String, Long>): Long {
34+
if (design.isEmpty()) {
35+
return 1
36+
}
37+
38+
cache[design]?.let { return it }
39+
40+
var node = trie
41+
var i = 0
42+
var num = 0L
43+
while (i < design.length) {
44+
val c = design[i]
45+
i++
46+
47+
node = node.children[c] ?: run {
48+
cache[design] = num
49+
return num
50+
}
51+
52+
node.pattern?.let {
53+
num += numPossibilities(design.substring(i), trie, cache)
54+
}
55+
}
56+
57+
cache[design] = num
58+
return num
59+
}
60+
61+
override fun solveLevel1(): Any {
62+
val trie = buildTrie(patterns)
63+
return designs.count { design -> numPossibilities(design, trie, mutableMapOf()) > 0 }
64+
}
65+
66+
override fun solveLevel2(): Any {
67+
val trie = buildTrie(patterns)
68+
return designs.sumOf { design -> numPossibilities(design, trie, mutableMapOf()) }
69+
}
70+
}

src/test/kotlin/y24/Day19Test.kt

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package y24
2+
3+
import common.puzzle.Input
4+
import org.junit.jupiter.api.Assertions.assertEquals
5+
import org.junit.jupiter.api.Test
6+
7+
internal class Day19Test {
8+
private val sample = Input("""
9+
r, wr, b, g, bwu, rb, gb, br
10+
11+
brwrr
12+
bggr
13+
gbbr
14+
rrbgbr
15+
ubwu
16+
bwurrg
17+
brgr
18+
bbrgwb
19+
""".trimIndent())
20+
21+
private val day = Day19(sample)
22+
23+
@Test
24+
fun solveLevel1() {
25+
assertEquals(6, day.solveLevel1())
26+
}
27+
28+
@Test
29+
fun solveLevel2() {
30+
assertEquals(16L, day.solveLevel2())
31+
}
32+
}

0 commit comments

Comments
 (0)