Guest User

Untitled

a guest
Dec 24th, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.78 KB | None | 0 0
  1.   private def play(nextCupPointers: Array[Int], maxCup: Int, firstCup: Int, rounds: Int) = {
  2.     (1 to rounds).foldLeft(firstCup) {
  3.       case (startingCup, _) =>
  4.         val firstCupToMove = nextCupPointers(startingCup)
  5.         val secondCupToMove = nextCupPointers(firstCupToMove)
  6.         val thirdCupToMove = nextCupPointers(secondCupToMove)
  7.         val nextStartingCup = nextCupPointers(thirdCupToMove)
  8.         nextCupPointers(startingCup) = nextStartingCup
  9.         val cupsToMove = List(firstCupToMove, secondCupToMove, thirdCupToMove)
  10.         val cupToMoveAfter = List(1, 2, 3, 4).collectFirst {
  11.           case delta if startingCup - delta == 0 =>
  12.             cupsToMove.sorted.reverse.foldLeft(maxCup) {
  13.               case (currentMax, cupToMove) if cupToMove == currentMax => currentMax - 1
  14.               case (currentMax, _) => currentMax
  15.             }
  16.           case delta if !cupsToMove.contains(startingCup - delta) =>
  17.             startingCup - delta
  18.         }.get
  19.         nextCupPointers(thirdCupToMove) = nextCupPointers(cupToMoveAfter)
  20.         nextCupPointers(cupToMoveAfter) = firstCupToMove
  21.         nextStartingCup
  22.     }
  23.     nextCupPointers
  24.   }
  25.  
  26.   private def solvePartTwo(seedCups: List[Int]): Long = {
  27.     val maxCup = 1000000
  28.    
  29.     val nextCupPointers = Array.ofDim[Int](maxCup + 1)
  30.     seedCups.indices.foreach { cupIndex =>
  31.       nextCupPointers(seedCups(cupIndex)) = seedCups((cupIndex + 1) % seedCups.length)
  32.     }
  33.     nextCupPointers(seedCups.last) = seedCups.max + 1
  34.     (seedCups.max + 1 until maxCup).foreach { cup =>
  35.       nextCupPointers(cup) = cup + 1
  36.     }
  37.     nextCupPointers(maxCup) = seedCups.head
  38.    
  39.     play(nextCupPointers, maxCup, seedCups.head, rounds = 10000000)
  40.    
  41.     nextCupPointers(1).toLong * nextCupPointers(nextCupPointers(1))
  42.   }
Advertisement
Add Comment
Please, Sign In to add comment