generated from Jadarma/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathY2021D06.kt
49 lines (40 loc) · 1.65 KB
/
Y2021D06.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D06 : Solution {
/**
* A simulation model of a population of lantern fish.
* @constructor Initializes this population based on the days left of each fish's reproductive cycle.
*/
private class LanternFishPopulation(seed: List<Int>) {
private val cycles = LongArray(9) { 0L }
init {
seed.forEach { cycle ->
require(cycle in 0..8) { "Invalid reproduction cycle for a LanternFish." }
cycles[cycle]++
}
}
/** Pass a day in the simulation, and give birth to more fish. */
fun simulateDay() {
val fishThatWillGiveBirth = cycles[0]
for (age in 0..7) cycles[age] = cycles[age + 1]
cycles[8] = fishThatWillGiveBirth
cycles[6] += cycles[8]
}
/** Returns the total number of live fish at this point in the simulation. */
fun populationCount(): Long = cycles.sum()
}
/** Parse the input and return the [LanternFishPopulation] described in the input. */
private fun parseInput(input: String): LanternFishPopulation =
input
.splitToSequence(',')
.map { cycle -> cycle.toIntOrNull() ?: throw IllegalArgumentException() }
.let { LanternFishPopulation(it.toList()) }
override fun partOne(input: String) =
parseInput(input)
.apply { repeat(80) { simulateDay() } }
.populationCount()
override fun partTwo(input: String) =
parseInput(input)
.apply { repeat(256) { simulateDay() } }
.populationCount()
}