From 0aa30cca2aced969b4c029a597a35e6112f3e133 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Thu, 12 Dec 2024 18:56:24 +0100 Subject: [PATCH] Day 11 Part 2 --- 2024/src/main/kotlin/day11.kt | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/2024/src/main/kotlin/day11.kt b/2024/src/main/kotlin/day11.kt index d964150..9593a3d 100644 --- a/2024/src/main/kotlin/day11.kt +++ b/2024/src/main/kotlin/day11.kt @@ -1,31 +1,28 @@ fun main() { val input = readInputString("day11.txt").split(" ").map { it.toLong() } - val part1 = (1..25).fold(input) { result, _ -> - result.blink() - }.count() - + val part1 = input.blink(25) println("Part 1: $part1") - - val part2 = (1..75).fold(input) { result, _ -> - result.blink() - }.count() - + val part2 = input.blink(75) println("Part 2: $part2") - } -fun List.blink() = flatMap { - val str = "$it" +fun List.blink(count: Int) = fold(0L) { acc, stone -> acc + blink(stone, count) } + +val memo = mutableMapOf, Long>() +fun blink(stone: Long, count: Int): Long = memo.getOrPut(Pair(stone, count)) { + if (count == 0) return 1 + + val str = "$stone" val strLen = str.count() when { - it == 0L -> listOf(1L) - strLen % 2 == 0 -> listOf( - str.substring(0, strLen / 2).toLong(), - str.substring(strLen / 2).toLong() - ) - else -> listOf(it * 2024) + stone == 0L -> blink(1L, count - 1) + strLen % 2 == 0 -> + blink(str.substring(0, strLen / 2).toLong(), count - 1) + + blink(str.substring(strLen / 2).toLong(), count - 1) + + else -> blink(stone * 2024, count - 1) } -} \ No newline at end of file +}