Skip to content

Commit

Permalink
Finish 2024 day 19 both parts
Browse files Browse the repository at this point in the history
  • Loading branch information
tymscar committed Dec 19, 2024
1 parent 0d852cc commit 3fabe07
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
2 changes: 2 additions & 0 deletions 2024/kotlin/src/main/kotlin/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import com.tymscar.day15.solve as day15
import com.tymscar.day16.solve as day16
import com.tymscar.day17.solve as day17
import com.tymscar.day18.solve as day18
import com.tymscar.day19.solve as day19

fun main() {
day01()
Expand All @@ -38,4 +39,5 @@ fun main() {
day16()
day17()
day18()
day19()
}
17 changes: 16 additions & 1 deletion 2024/kotlin/src/main/kotlin/com/tymscar/day19/part1/part1.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package com.tymscar.day19.part1

private fun getValidDesigns(designs: List<String>, towels: List<String>): List<String> = designs
.filter {
Regex("""^(${towels.joinToString("|")})+$""")
.matches(it)
}

fun solve(input: String): String {
return input
val towels = input
.split("\n\n")[0]
.split(", ")
val designs = input
.split("\n\n")[1]
.lines()

return getValidDesigns(designs, towels)
.count()
.toString()
}
37 changes: 36 additions & 1 deletion 2024/kotlin/src/main/kotlin/com/tymscar/day19/part2/part2.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,40 @@
package com.tymscar.day19.part2

private fun isValidDesign(design: String, towels: List<String>): Boolean =
Regex("""^(${towels.joinToString("|")})+$""")
.matches(design)

private fun waysToMake(
design: String,
towels: List<String>,
memo: HashMap<String, Long>
): Long {
if (memo.contains(design)) return memo[design]!!
if (!isValidDesign(design, towels)) return 0

val result = towels.sumOf {
when {
design == it -> 1
design.startsWith(it) -> waysToMake(design.removePrefix(it), towels, memo)
else -> 0
}
}

memo[design] = result
return result
}

fun solve(input: String): String {
return input
val towels = input
.split("\n\n")[0]
.split(", ")
val designs = input
.split("\n\n")[1]
.lines()

val memo = HashMap<String, Long>()

return designs
.sumOf { waysToMake(it, towels, memo) }
.toString()
}

0 comments on commit 3fabe07

Please sign in to comment.