generated from kotlin-hands-on/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f187598
commit 9d55b16
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |