Skip to content

Commit

Permalink
Day 11
Browse files Browse the repository at this point in the history
  • Loading branch information
luanpotter committed Dec 16, 2024
1 parent 19a3b2d commit 3ee01d3
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/main/kotlin/xyz/luan/advent/day11/Main.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package xyz.luan.advent.day11

import xyz.luan.advent.util.readFile

fun main() {
val input = parse(readFile("day11/input"))

val stones = Stones()
stones.ingest(input)
stones.evolve(75)
val result = stones.compute()

println("B: $result")
}

private fun parse(input: List<String>): List<Long> {
val line = input.filterNot { it.isBlank() }.single()
return line
.split(" ")
.map { it.trim().toLong() }
}

class Stones {
private val stones = mutableMapOf<Long, Long>()

private fun rule(value: Long): List<Long> {
val str = value.toString()
return when {
value == 0L -> listOf(1)
str.length % 2 == 0 -> listOf(
str.substring(0..<str.length / 2).toLong(),
str.substring(str.length / 2).toLong(),
)

else -> listOf(value * 2024)
}
}

private fun inc(stone: Long, amount: Long = 1) {
stones[stone] = (stones[stone] ?: 0) + amount
}

fun ingest(stones: List<Long>) {
stones.forEach { inc(it) }
}

fun evolve(blinks: Int) {
repeat(blinks) { evolveOnce() }
}

fun compute(): Long {
return stones.values.sum()
}

private fun evolveOnce() {
for ((stone, count) in stones.toList()) {
inc(stone, -count)
rule(stone).forEach { inc(it, count) }
}
}
}
1 change: 1 addition & 0 deletions src/main/resources/xyz/luan/advent/day11/input
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
9694820 93 54276 1304 314 664481 0 4
20 changes: 20 additions & 0 deletions src/test/kotlin/xyz/luan/advent/day11/Day11Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package xyz.luan.advent.day11

import org.junit.jupiter.api.Test
import xyz.luan.advent.day11.Stones
import kotlin.test.assertEquals

class Day11Test {
@Test
fun `simplest case`() {
testCase(listOf(125, 17), 6, 22)
testCase(listOf(125, 17), 25, 55312)
}

private fun testCase(input: List<Long>, blink: Int, result: Long) {
val stones = Stones()
stones.ingest(input)
stones.evolve(blink)
assertEquals(result, stones.compute())
}
}

0 comments on commit 3ee01d3

Please sign in to comment.