Skip to content

Instantly share code, notes, and snippets.

@nudded
Created December 3, 2017 19:29
Show Gist options
  • Select an option

  • Save nudded/d6e46e45da3912fea5883c690806cd72 to your computer and use it in GitHub Desktop.

Select an option

Save nudded/d6e46e45da3912fea5883c690806cd72 to your computer and use it in GitHub Desktop.
Day 3
MOVE_ARRAY = [[0,1],[-1,0],[0,-1],[1,0]]
ODD_SQUARES = (1..10000).select(&:odd?).map {|i| i * i}
# move the pointer in the spiral to the next position
def move(counter, x, y)
# we should go right if we are a square number
sqrt_counter = Math.sqrt(counter).to_i
sqrt_counter = sqrt_counter.odd? ? sqrt_counter : sqrt_counter - 1
return [x+1, y] if ODD_SQUARES.include? counter
lowest_right_corner = sqrt_counter * sqrt_counter
move_array_index = (1..4).detect do |i|
counter < (lowest_right_corner + i * (sqrt_counter.to_i + 1))
end
# minus one, so that the math works out
move_array_index -= 1
MOVE_ARRAY[move_array_index].zip([x,y]).map {|v1,v2| v1 + v2}
end
# fill the newly calculated value in the spiral
def fill_value(spiral, x, y)
new_value = 0
# Get the eight surrounding values (we don't care that they are not filled in)
(-1..1).each do |i|
(-1..1).each do |j|
new_value += get_value(spiral, x-i, y-j)
end
end
set_value(spiral, x, y, new_value)
new_value
end
def get_value(spiral, x, y)
spiral[x][y]
end
def set_value(spiral, x, y, value)
spiral[x][y] = value
end
#starting spiral
spiral = []
max_size = 100
(0...max_size).each do |i|
spiral << Array.new(max_size, 0)
end
# initialize the middle of the spiral
x = max_size / 2
y = max_size / 2
counter = 1
set_value(spiral, x, y, 1)
loop do
x, y = move(counter, x, y)
value = fill_value(spiral, x, y)
counter += 1
if value > 289326
puts value
exit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment