Skip to content

Instantly share code, notes, and snippets.

@rthbound
Created December 3, 2017 16:49
Show Gist options
  • Save rthbound/e685375656ec554ab4655b266ba8e0b3 to your computer and use it in GitHub Desktop.
Save rthbound/e685375656ec554ab4655b266ba8e0b3 to your computer and use it in GitHub Desktop.
aoc-2017-p2.rb
class SpiralFantasy
def initialize(number)
@number = number.to_i
@grid = { Complex(0,0) => 1 }
end
def call
draw.values.max
end
private
def draw
start = Complex(0,0)
directions = [ :right, :up, :left, :down ]
while(@grid.values.max <= @number) do
case directions[0]
when :right
start += Complex(1,0)
@grid.merge!({ start => next_cell(start) })
directions.rotate! if start.real == -(start.imag - 1)
when :up
start += Complex(0,1)
@grid.merge!({ start => next_cell(start) })
directions.rotate! if start.real.abs == start.imag.abs
when :left
start += Complex(-1,0)
@grid.merge!({ start => next_cell(start) })
directions.rotate! if start.real.abs == start.imag.abs
when :down
start += Complex(0,-1)
@grid.merge!({ start => next_cell(start) })
directions.rotate! if start.real.abs == start.imag.abs
end
end
@grid
end
def next_cell(current)
keys = [
current + Complex(-1, 0),
current + Complex( 1, 0),
current + Complex( 1, 1),
current + Complex(-1,-1),
current + Complex(-1, 1),
current + Complex( 1,-1),
current + Complex( 0, 1),
current + Complex( 0,-1),
]
@grid.values_at(*keys).compact.inject(:+)
end
end
puts SpiralFantasy.new(ARGV[0]).call
@rthbound
Copy link
Author

rthbound commented Dec 3, 2017

Usage: ruby spiral_fantasy.rb 325489

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment