-
-
Save waynejo/ab5cd673970a9c1138a83b6acfab95b3 to your computer and use it in GitHub Desktop.
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
import java.io.FileInputStream | |
import scala.io.StdIn | |
@main def solve15() = | |
def solve1(turn: Int, history: Vector[Int]): Int = { | |
val result = history.init.lastIndexOf(history.last) match { | |
case -1 => | |
0 | |
case idx => | |
turn - idx - 2 | |
} | |
if turn == 2020 then | |
result | |
else | |
solve1(turn + 1, history :+ result) | |
} | |
def solve2(numbers: Vector[Int]): Int = { | |
def _solve2(turn: Int, history: Map[Int, Int], remains: Vector[Int], lastNumber: Int): Int = { | |
if turn == 30000000 + 1 then | |
lastNumber | |
else | |
val nextHistory = history.updated(lastNumber, turn - 1) | |
val nextTurn = turn + 1 | |
(remains.headOption, history.get(lastNumber)) match { | |
case (Some(number), _) => | |
_solve2(nextTurn, nextHistory, remains.tail, number) | |
case (_, Some(idx)) => | |
_solve2(nextTurn, nextHistory, remains, turn - idx - 1) | |
case _ => | |
_solve2(nextTurn, nextHistory, remains, 0) | |
} | |
} | |
_solve2(2, Map(), numbers.tail, numbers.head) | |
} | |
val in = new FileInputStream("example15-1.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
val numbers = inputs.next().split(",").toVector.map { _.toInt } | |
val answer1 = solve1(numbers.length + 1, numbers) | |
println(answer1) | |
val answer2 = solve2(numbers) | |
println(answer2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment