Skip to content

Commit 64e4b9f

Browse files
committed
Day 9
1 parent 6676238 commit 64e4b9f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

2018/9.scala

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
val numPlayers = 458
2+
val highestMarble = 7201900
3+
4+
case class Turn(currentPlayer: Int, game: Seq[Int], scores: Map[Int, Long])
5+
6+
def shiftLeft[T](sequence: Seq[T], shift: Int): Seq[T] =
7+
if (shift < 0) shiftRight(sequence, Math.abs(shift))
8+
else shiftRight(sequence, sequence.size - shift)
9+
10+
def shiftRight[T](sequence: Seq[T], shift: Int): Seq[T] =
11+
if (shift == 0 || sequence.isEmpty) {
12+
sequence
13+
} else {
14+
val split = (sequence.size - shift) % sequence.size
15+
sequence.drop(split) ++ sequence.take(split)
16+
}
17+
18+
19+
def printGame(turn: Turn): Unit = {
20+
println(turn.game.mkString(", "))
21+
}
22+
23+
val lastTurn = (0 to highestMarble).foldLeft(Turn(0, Vector.empty, Map().withDefaultValue(0))) {
24+
case (Turn(currentPlayer, game, scores), marble) =>
25+
val (newGame, newScores) = if (marble % 23 == 0 && marble > 0) {
26+
val backSeven = shiftRight(game, 7)
27+
val newScores = scores + (currentPlayer -> (scores(currentPlayer) + marble + backSeven.head))
28+
29+
(backSeven.drop(1), newScores)
30+
} else {
31+
val shifted = shiftLeft(game, 2)
32+
(marble +: shifted, scores)
33+
}
34+
35+
Turn((currentPlayer + 1) % numPlayers, newGame, newScores)
36+
}
37+
38+
println(lastTurn.scores.values.max)

0 commit comments

Comments
 (0)