Skip to content

Commit

Permalink
Solve Day 11
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulWoitaschek committed Dec 11, 2024
1 parent f187598 commit 9d55b16
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
50 changes: 50 additions & 0 deletions 2024/src/main/kotlin/aoc/year2024/Day11.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package aoc.year2024

import aoc.library.Puzzle

object Day11 : Puzzle<Long, Long>(day = 11) {

override fun solvePart1(input: String): Long = solve(input, blinks = 25)

override fun solvePart2(input: String): Long = solve(input, blinks = 75)

private fun solve(
input: String,
blinks: Int,
): Long {
var numbers = parse(input)
repeat(blinks) {
numbers = numbers.blink()
}
return numbers.values.sum()
}

private fun parse(input: String): Map<Long, Long> = input.split(" ")
.groupingBy(String::toLong)
.eachCount()
.mapValues { it.value.toLong() }

private fun Map<Long, Long>.blink(): Map<Long, Long> {
val afterBlink = mutableMapOf<Long, Long>()
forEach { (number, count) ->
number.blink().forEach { newNumber ->
val current = afterBlink[newNumber] ?: 0
afterBlink[newNumber] = current + count
}
}
return afterBlink
}

private fun Long.blink(): List<Long> = when {
this == 0L -> listOf(1)
toString().length % 2 == 0 -> {
val asString = this.toString()
val center = asString.length / 2
listOf(
asString.take(center).toLong(),
asString.drop(center).toLong(),
)
}
else -> listOf(this * 2024)
}
}
24 changes: 24 additions & 0 deletions 2024/src/test/kotlin/aoc/year2024/Day11Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package aoc.year2024

import aoc.library.solvePart1
import aoc.library.solvePart2
import io.kotest.matchers.longs.shouldBeExactly
import org.junit.jupiter.api.Test

class Day11Test {

@Test
fun part1TestInput() {
Day11.solvePart1("125 17") shouldBeExactly 55312
}

@Test
fun part1() {
Day11.solvePart1() shouldBeExactly 194557
}

@Test
fun part2() {
Day11.solvePart2() shouldBeExactly 231532558973909
}
}

0 comments on commit 9d55b16

Please sign in to comment.