Skip to content

Instantly share code, notes, and snippets.

@pocari
Last active August 29, 2015 14:20
Show Gist options
  • Save pocari/465a5a11d5f0a9f7b81e to your computer and use it in GitHub Desktop.
Save pocari/465a5a11d5f0a9f7b81e to your computer and use it in GitHub Desktop.
ラーメンマーク
class DirectionGenerator
RIGHT = [ 0, 1]
DOWN = [ 1, 0]
LEFT = [ 0, -1]
UP = [-1, 0]
def each
[RIGHT, DOWN, LEFT, UP].cycle.each do |dir|
yield dir
end
end
def reverse_each
[DOWN, RIGHT, UP, LEFT].cycle.each do |dir|
yield dir
end
end
end
class StepGenerator
include Enumerable
def initialize(pivot)
@pivot = pivot
end
def each
return enum_for unless block_given?
dg = DirectionGenerator.new.enum_for(:each)
1.upto(@pivot + 1) do |n|
next_dir = dg.next
n.times do
yield next_dir
end
end
reverse_dg = DirectionGenerator.new.enum_for(:reverse_each)
next_dir = reverse_dg.next
@pivot.times do
yield next_dir
end
(@pivot + 1).downto(1) do |n|
next_dir = reverse_dg.next
n.times do
yield next_dir
end
end
end
end
class RamenBoard
def initialize(n)
pivot = n * 4
@step_generator = StepGenerator.new(pivot)
@board = Array.new(pivot + 1 ) { Array.new(pivot * 2 + 2, ' ') }
@init_row = pivot / 2
@init_col = @init_row
end
def fill_ramen
@board[@init_row][@init_col] = "#"
@step_generator.inject([@init_row, @init_col]) do |acc, (delta_r, delta_c)|
r, c = acc
@board[r + delta_r][c + delta_c] = "#"
[r + delta_r, c + delta_c]
end
self
end
def to_s
@board.map(&:join)
end
end
1.upto(100) do |n|
puts "n = #{n}"
puts RamenBoard.new(n).fill_ramen.to_s
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment