Skip to content

Commit

Permalink
AoC 2024 Day 19 Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
GeistInDerSH committed Dec 20, 2024
1 parent 32641c8 commit 53bafea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
36 changes: 21 additions & 15 deletions src/main/kotlin/com/geistindersh/aoc/year2024/Day19.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,20 @@ import java.util.PriorityQueue
class Day19(
private val patterns: Set<String>,
private val designs: List<String>,
private val debug: Boolean = false,
) {
constructor(dataFile: DataFile, debug: Boolean = false) : this(fileToString(2024, 19, dataFile), debug)
constructor(input: String, debug: Boolean = false) : this(
constructor(dataFile: DataFile) : this(fileToString(2024, 19, dataFile))
constructor(input: String) : this(
input
.substringBefore("\n")
.split(',')
.map { it.trim() }
.sortedByDescending { it.length }
.toSet(),
input.substringAfter("\n").split("\n").drop(1),
debug,
)

private fun String.isValid(): Boolean {
if (this.isEmpty()) return true
if (debug) println(this)

val queue = PriorityQueue<String>(compareBy { it.length }).apply { add(this@isValid) }
val seen = mutableSetOf<String>()
Expand All @@ -33,7 +30,6 @@ class Day19(
if (head.isBlank()) return true
if (!seen.add(head)) continue
if (head in patterns) return true
if (debug) println(head)

for (pattern in patterns) {
if (!head.startsWith(pattern)) continue
Expand All @@ -44,18 +40,28 @@ class Day19(
return false
}

init {
println()
}
private fun String.validComboCount(): Long {
val queue = PriorityQueue<String>(compareByDescending { it.length }).apply { add(this@validComboCount) }
val memory = mutableMapOf<String, Long>(this to 1L)

fun part1() =
designs.count {
val v = it.isValid()
println("$it: $v")
v
while (queue.isNotEmpty()) {
val head = queue.poll()

for (pattern in patterns) {
if (!head.startsWith(pattern)) continue
val substring = head.substringAfter(pattern)
if (substring !in memory) {
queue.add(substring)
}
memory[substring] = memory.getOrDefault(substring, 0L) + memory[head]!!
}
}
return memory.getOrDefault("", 0L)
}

fun part1() = designs.count { it.isValid() }

fun part2() = 0
fun part2() = designs.filter { it.isValid() }.sumOf { it.validComboCount() }
}

fun day19() {
Expand Down
3 changes: 1 addition & 2 deletions src/test/kotlin/com/geistindersh/aoc/year2024/Day19Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ class Day19Test {

@Test
fun part2() {
assertEquals(-1, Day19(DataFile.Example).part2())
assertEquals(-1, Day19(DataFile.Part1).part2())
assertEquals(16, Day19(DataFile.Example).part2())
}
}

0 comments on commit 53bafea

Please sign in to comment.