Advertisement
Guest User

Untitled

a guest
Jan 10th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.23 KB | None | 0 0
  1. import scala.annotation.tailrec
  2. import scala.language.higherKinds
  3.  
  4. object Elves {
  5.  
  6.   val players = 410
  7.   val stones = 7205900
  8.  
  9.   type L[A] = Vector[A]
  10.   type S[A] = Vector[A]
  11.  
  12.   def main(args: Array[String]): Unit = {
  13.  
  14.     val scores = f(Vector(0, 1), 1, 2, Vector.fill(players+1)(0))
  15.     println(scores.max)
  16.   }
  17.  
  18.   @tailrec
  19.   def f(state: L[Int], currentPosition: Int, currentMarble: Int, scores: S[Long]): S[Long] = {
  20.     if (currentMarble > stones) return scores
  21.  
  22.     val player = ((currentMarble - 1) % players) + 1
  23.  
  24.     val (newState, newPos, scored) = if (currentMarble % 23 != 0) {
  25.       (currentMarble +: state.rotate(currentPosition + 2) , 0, 0)
  26.     }
  27.     else {
  28.       val (extraMarble, tail) = state.rotate(currentPosition - 7).pop()
  29.       (tail, 0, currentMarble + extraMarble)
  30.     }
  31.  
  32.     f(newState, newPos, currentMarble + 1, scores.updated(player, scored + scores(player)))
  33.   }
  34.  
  35.  
  36.   implicit class State[A](l: L[A]) {
  37.  
  38.     def rotate(pos: Int): L[A] = {
  39.       val k = index(pos, l.size)
  40.       val (front, back) = l.splitAt(k)
  41.       back ++ front
  42.     }
  43.  
  44.     def pop(): (A, L[A]) = {
  45.       (l.head, l.tail)
  46.     }
  47.  
  48.     private def index(i: Int, n: Int): Int = {
  49.       (n + i) % n
  50.     }
  51.  
  52.   }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement