|
| 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 | +} |
0 commit comments