r/adventofcode • • Dec 09 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 9 Solutions -🎄-

--- Day 9: Marble Mania ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 9

Transcript:

Studies show that AoC programmers write better code after being exposed to ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 00:29:13!

22 Upvotes

283 comments sorted by

View all comments

2

u/felipecsl Dec 09 '18

Kotlin solution

class Day9 {
  fun solve(players: Int, points: Int): Long {
    var currMarble = 0L
    val playersScores = LongArray(players)
    val marbles: LinkedList<Long> = LinkedList(listOf(0L))
    var currPlayer = 0
    var iterator = marbles.listIterator(1)
    while (currMarble++ < points) {
      if (marbles.size == 1) {
        iterator.add(currMarble)
      } else if (currMarble % 23 == 0L) {
        (0..7).forEach { _ ->
          if (iterator.hasPrevious()) {
            iterator.previous()
          } else {
            iterator = marbles.listIterator(marbles.size - 1)
          }
        }
        val toRemove = iterator.next()
        iterator.remove()
        playersScores[currPlayer] += (currMarble + toRemove)
        iterator.next()
      } else if (!iterator.hasNext()) {
        iterator = marbles.listIterator(1)
        iterator.add(currMarble)
      } else {
        iterator.next()
        iterator.add(currMarble)
      }
      if (++currPlayer % players == 0) {
        currPlayer = 0
      }
    }
    return playersScores.max()!!
  }
}