Skip to content

Instantly share code, notes, and snippets.

@horace-velmont
Last active March 19, 2021 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save horace-velmont/d62e2ee1c1a2bb3ef3abaa2ef94a12ad to your computer and use it in GitHub Desktop.
Save horace-velmont/d62e2ee1c1a2bb3ef3abaa2ef94a12ad to your computer and use it in GitHub Desktop.
advent of code - day15
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))
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