Day 11 Part 2
This commit is contained in:
parent
9e8f49963c
commit
0aa30cca2a
1 changed files with 16 additions and 19 deletions
|
@ -1,31 +1,28 @@
|
||||||
fun main() {
|
fun main() {
|
||||||
val input = readInputString("day11.txt").split(" ").map { it.toLong() }
|
val input = readInputString("day11.txt").split(" ").map { it.toLong() }
|
||||||
|
|
||||||
val part1 = (1..25).fold(input) { result, _ ->
|
val part1 = input.blink(25)
|
||||||
result.blink()
|
|
||||||
}.count()
|
|
||||||
|
|
||||||
println("Part 1: $part1")
|
println("Part 1: $part1")
|
||||||
|
|
||||||
|
val part2 = input.blink(75)
|
||||||
val part2 = (1..75).fold(input) { result, _ ->
|
|
||||||
result.blink()
|
|
||||||
}.count()
|
|
||||||
|
|
||||||
println("Part 2: $part2")
|
println("Part 2: $part2")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun List<Long>.blink() = flatMap {
|
fun List<Long>.blink(count: Int) = fold(0L) { acc, stone -> acc + blink(stone, count) }
|
||||||
val str = "$it"
|
|
||||||
|
val memo = mutableMapOf<Pair<Long, Int>, 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()
|
val strLen = str.count()
|
||||||
|
|
||||||
when {
|
when {
|
||||||
it == 0L -> listOf(1L)
|
stone == 0L -> blink(1L, count - 1)
|
||||||
strLen % 2 == 0 -> listOf(
|
strLen % 2 == 0 ->
|
||||||
str.substring(0, strLen / 2).toLong(),
|
blink(str.substring(0, strLen / 2).toLong(), count - 1) +
|
||||||
str.substring(strLen / 2).toLong()
|
blink(str.substring(strLen / 2).toLong(), count - 1)
|
||||||
)
|
|
||||||
else -> listOf(it * 2024)
|
else -> blink(stone * 2024, count - 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue