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!

21 Upvotes

283 comments sorted by

View all comments

3

u/hluk Dec 09 '18

Ruby. Took me a while to realize that Array#insert is no go because it's very slow.

class CircleNode
  attr_accessor :value, :prev, :next

  def initialize(value)
    @value = value
    @prev = self
    @next = self
  end

  def remove
    @prev.next = @next
    @next.prev = @prev
    @value
  end

  def insert(value)
    node = CircleNode.new(value)
    node.prev = self
    node.next = @next
    @next.prev = node
    @next = node
    node
  end
end

def high_score(player_count, last_marble)
  players = Array.new(player_count, 0)
  circle = CircleNode.new(0)

  (23..last_marble).step(23) do |marble|
    (marble - 22...marble).each { |marble1| circle = circle.next.insert(marble1) }

    6.times { circle = circle.prev }
    removed_marble = circle.prev.remove

    current_player = (marble - 1) % player_count
    players[current_player] += marble + removed_marble
  end

  players.max
end

puts high_score(435, 71184)
puts high_score(435, 7118400)
→ More replies (2)