diff --git a/2024/kotlin/src/main/kotlin/Main.kt b/2024/kotlin/src/main/kotlin/Main.kt index 0e39d8f..6ba636a 100644 --- a/2024/kotlin/src/main/kotlin/Main.kt +++ b/2024/kotlin/src/main/kotlin/Main.kt @@ -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() @@ -38,4 +39,5 @@ fun main() { day16() day17() day18() + day19() } \ No newline at end of file diff --git a/2024/kotlin/src/main/kotlin/com/tymscar/day19/part1/part1.kt b/2024/kotlin/src/main/kotlin/com/tymscar/day19/part1/part1.kt index 8c21975..ed085b4 100644 --- a/2024/kotlin/src/main/kotlin/com/tymscar/day19/part1/part1.kt +++ b/2024/kotlin/src/main/kotlin/com/tymscar/day19/part1/part1.kt @@ -1,5 +1,20 @@ package com.tymscar.day19.part1 +private fun getValidDesigns(designs: List, towels: List): List = 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() } diff --git a/2024/kotlin/src/main/kotlin/com/tymscar/day19/part2/part2.kt b/2024/kotlin/src/main/kotlin/com/tymscar/day19/part2/part2.kt index 857f536..743696b 100644 --- a/2024/kotlin/src/main/kotlin/com/tymscar/day19/part2/part2.kt +++ b/2024/kotlin/src/main/kotlin/com/tymscar/day19/part2/part2.kt @@ -1,5 +1,40 @@ package com.tymscar.day19.part2 +private fun isValidDesign(design: String, towels: List): Boolean = + Regex("""^(${towels.joinToString("|")})+$""") + .matches(design) + +private fun waysToMake( + design: String, + towels: List, + memo: HashMap +): 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() + + return designs + .sumOf { waysToMake(it, towels, memo) } + .toString() }