-
-
Save horace-velmont/d62e2ee1c1a2bb3ef3abaa2ef94a12ad to your computer and use it in GitHub Desktop.
advent of code - day15
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
package day15 | |
import day15.Day15.{Memory, solve} | |
import java.io.FileInputStream | |
import scala.annotation.tailrec | |
import scala.io.StdIn | |
object Day15: | |
case class Memory(dict: Map[Int, Int] = Map.empty, lastSpoken: Int = -1) | |
@tailrec | |
def solve(starting: Array[Int], goal: Int, memory: Memory = new Memory(), turn: Int = 1): Int = { | |
val lastSpoken = memory.lastSpoken | |
val dict = memory.dict | |
val nextTurn = turn + 1 | |
turn match { | |
case _ if (turn > goal) => lastSpoken | |
case x if x <= starting.length => { | |
val speak = starting(turn - 1) | |
solve(starting, goal, Memory(dict.updated(lastSpoken, turn), starting(turn - 1)), nextTurn) | |
} | |
case _ => { | |
if (dict.contains(lastSpoken)) { | |
val speak = turn - dict.get(lastSpoken).get | |
solve(starting, goal, Memory(dict.updated(lastSpoken, turn), speak), nextTurn) | |
} else { | |
solve(starting, goal, Memory(dict.updated(lastSpoken, turn), 0), nextTurn) | |
} | |
} | |
} | |
} | |
@main def solve15_1() = | |
val in = new FileInputStream("src/example15-1.in") | |
System.setIn(in) | |
val inputs = StdIn.readLine().split(",").map(_.toInt) | |
println(solve(inputs, 2020)) | |
println(solve(inputs, 30000000)) | |
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
package day15 | |
import org.junit.Assert._ | |
import org.junit.Test | |
class Day15Test { | |
@Test def test(): Unit = { | |
assertEquals(1, Day15.solve(Array(1, 3, 2), 2020)) | |
assertEquals(436, Day15.solve(Array(0, 3, 6), 2020)) | |
assertEquals(27, Day15.solve(Array(1, 2, 3), 2020)) | |
assertEquals(78, Day15.solve(Array(2, 3, 1), 2020)) | |
assertEquals(438, Day15.solve(Array(3, 2, 1), 2020)) | |
assertEquals(1836, Day15.solve(Array(3, 1, 2), 2020)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment