Skip to content

Instantly share code, notes, and snippets.

@Ynote
Last active April 1, 2020 11:52
Show Gist options
  • Save Ynote/1aebaefcc4b3beb5cfa0687213ead949 to your computer and use it in GitHub Desktop.
Save Ynote/1aebaefcc4b3beb5cfa0687213ead949 to your computer and use it in GitHub Desktop.
class Snail
def initialize(data)
@data = data
@direction = :right
end
def call
values = []
values << get(x, y) while move
values
end
private
attr_accessor :data, :x, :y
def move
if @x.nil?
@x = 0
@y = 0
return true
end
change_direction unless fetch(@y + move_y, @x + move_x)
@x += move_x
@y += move_y
# Return false if ended
fetch(@y, @x)
end
def change_direction
directions = %i[right down left up]
@direction =
directions[directions.index(@direction) + 1] || directions.first
end
def fetch(y, x)
return if x < 0 || y < 0
data.dig(y, x)
end
def get(x, y)
value = fetch(y, x) || return
data[y][x] = nil
value
end
def move_x
case @direction
when :right then 1
when :left then -1
else
0
end
end
def move_y
case @direction
when :down then 1
when :up then -1
else
0
end
end
end
p Snail.new([
%w[A B C D E F G H],
%w[I J K L M N O P],
%w[Q R S T U V W X],
%w[Y Z 0 1 2 3 4 5],
%w[6 7 8 9 10 11 12 13],
%w[14 15 16 17 18 19 20 21],
]).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment