-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDay15.kt
32 lines (27 loc) · 945 Bytes
/
Day15.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
/*
* Copyright (c) 2020 by Todd Ginsberg
*/
/**
* Advent of Code 2020, Day 15 - Rambunctious Recitation
* Problem Description: http://adventofcode.com/2020/day/15
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day15/
*/
package com.ginsberg.advent2020
class Day15(input: String) {
private val startingNumbers = input.split(",").map { it.toInt() }
fun solve(turns: Int): Int =
memoryGame().drop(turns-1).first()
private fun memoryGame(): Sequence<Int> = sequence {
yieldAll(startingNumbers)
val memory = startingNumbers.mapIndexed { index, i -> i to index }.toMap().toMutableMap()
var turns = startingNumbers.size
var sayNext = 0
while(true) {
yield(sayNext)
val lastTimeSpoken = memory[sayNext] ?: turns
memory[sayNext] = turns
sayNext = turns - lastTimeSpoken
turns++
}
}
}