Commit 089e50ba authored by Alexander Gehrke's avatar Alexander Gehrke
Browse files

[day15] solution

parent c6a0a54f
......@@ -11,7 +11,8 @@ lazy val root = project
"-Yexplicit-nulls",
"-language:strict-equality",
),
libraryDependencies += "org.typelevel" %% "cats-core" % "2.3.0"
libraryDependencies += "org.typelevel" %% "cats-core" % "2.3.0",
)
.enablePlugins(JmhPlugin)
Runtime / unmanagedSources += baseDirectory.value / "input",
Runtime / unmanagedSources += baseDirectory.value / "input"
addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.4.6")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")
package aoc2020
import aoc2020.lib._
import cats.implicits.given
import scala.math.{min,max}
import cats._, cats.implicits.given
......
package aoc2020
import aoc2020.lib._
def day15(input: List[String]): String =
val starting: Map[Long, Long] = parse(input.head)
val (num2020, _) = playMut(starting, 2020)
val (num30mil, _) = playMut(starting, 30000000)
s"""2020th spoken number: $num2020
|30 millionth spoken number: $num30mil
""".stripMargin
def parse(input: String): Map[Long, Long] =
input.split(",").nn
.zipWithIndex
.map(t => (t._1.toLong, t._2 + 1L))
.toMap
def play(starting: Map[Long, Long], maxTurns: Long) =
val (lastNum, lastTurn) = starting.maxBy(_._2)
(lastTurn to maxTurns-1).foldLeft((lastNum, starting - lastNum)){
case ((last, spoken), turn) =>
val next = spoken.get(last).map(turn - _).getOrElse(0L)
val nowSpoken = spoken.updated(last, turn)
(next, nowSpoken)
}
/* about twice as fast for a single run */
import scala.collection.mutable
def playMut(starting: Map[Long, Long], maxTurns: Long) =
val (lastNum, lastTurn) = starting.maxBy(_._2)
val spoken = mutable.Map.from(starting - lastNum)
var last: Long = lastNum
for (turn <- (lastTurn to maxTurns-1)) {
val next = spoken.get(last).map(turn - _).getOrElse(0L)
spoken += last -> turn
last = next
}
(last, spoken)
......@@ -16,6 +16,7 @@ package aoc2020
case 12 => input()(day12)
case 13 => input()(day13)
case 14 => input()(day14)
case 15 => input()(day15)
case _ => "No such day implemented"
}
if (sample.nonEmpty) println("SAMPLE VALUES!")
......
package aoc2020
import org.openjdk.jmh.annotations._
import java.util.concurrent.TimeUnit
object Input { val in = parse("2,1,10,11,0,6") }
class Benchs {
@Benchmark
@BenchmarkMode(Array(Mode.AverageTime))
@OutputTimeUnit(TimeUnit.MICROSECONDS)
def measureAvgTime = playMut(Input.in, 2020)
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment