-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay15RambunctiousRecitation.kt
33 lines (28 loc) · 1.47 KB
/
Day15RambunctiousRecitation.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
package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day15RambunctiousRecitation(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val startingNumbers by lazy { input.split(",").map(String::toInt) }
override fun partOne() = startingNumbers.playGame(2020)
override fun partTwo() = startingNumbers.playGame(30_000_000)
companion object {
private fun List<Int>.playGame(turnCount: Int) =
(1..turnCount)
.fold(Pair(mutableMapOf<Int, List<Int>>(), -1)) { (memoryMap, lastNumberSpoken), turn ->
if (turn <= size) {
memoryMap[this[turn - 1]] = listOfNotNull(memoryMap.getOrDefault(this[turn - 1], emptyList()).lastOrNull(), turn)
memoryMap to this[turn - 1]
} else {
if (memoryMap[lastNumberSpoken]!!.size == 1) {
memoryMap[0] = listOfNotNull(memoryMap.getOrDefault(0, emptyList()).lastOrNull(), turn)
memoryMap to 0
} else {
val age = memoryMap[lastNumberSpoken]!!.last() - memoryMap[lastNumberSpoken]!!.first()
memoryMap[age] = listOfNotNull(memoryMap.getOrDefault(age, emptyList()).lastOrNull(), turn)
memoryMap to age
}
}
}
.second
}
}