Skip to content

Instantly share code, notes, and snippets.

@obelisk68
Last active November 22, 2017 01:43
Show Gist options
  • Save obelisk68/df6815a9eb65fa8d0c4455351c8d8692 to your computer and use it in GitHub Desktop.
Save obelisk68/df6815a9eb65fa8d0c4455351c8d8692 to your computer and use it in GitHub Desktop.
数学パズル
Square = 6
is_used = Array.new(Square + 1) {Array.new(Square + 1) {[false, false]}}
count = 0
route = lambda do |x, y, is_first_time|
if x == Square and y == Square
if is_first_time
route.call(0, 0, false)
else
count += 1
end
end
if x < Square
unless is_used[x][y][0]
is_used[x][y][0] = true
route.call(x + 1, y, is_first_time)
is_used[x][y][0] = false
end
end
if y < Square
unless is_used[x][y][1]
is_used[x][y][1] = true
route.call(x, y + 1, is_first_time)
is_used[x][y][1] = false
end
end
end
route.call(0, 0, true)
puts count
def route(width, height, back_y)
return (back_y == height) ? back_y : back_y + 2 if width == 1
return (back_y.zero?) ? 2 : 1 if height == 1
total = 0
if back_y.zero?
height.times {|i| total += 2 * route(width - 1, height, i + 1)}
else
back_y.upto(height) {|i| total += route(width - 1, height, i)}
total += route(width, height - 1, back_y - 1)
end
total
end
puts route(6, 6, 0)
width, height = 7, 4
str = ""
tatami = Array.new(height + 2) do |h|
Array.new(width + 2) do |w|
(h.zero? or w.zero? or h == height + 1 or w == width + 1) ? -1 : 0
end
end
print_tatami = lambda do
1.upto(height) do |i|
1.upto(width) do |j|
if tatami[i][j] == tatami[i][j + 1] or tatami[i][j] == tatami[i][j - 1]
str += "-"
end
if tatami[i][j] == tatami[i + 1][j] or tatami[i][j] == tatami[i - 1][j]
str += "|"
end
end
str += "\n"
end
str += "\n"
end
set_tatami = lambda do |h, w, id|
if h == height + 1
print_tatami.call
elsif w == width + 1
set_tatami.call(h + 1, 1, id)
elsif tatami[h][w] > 0
set_tatami.call(h, w + 1, id)
else
if tatami[h - 1][w - 1] == tatami[h - 1][w] or
tatami[h - 1][w - 1] == tatami[h][w - 1]
if tatami[h][w + 1].zero?
tatami[h][w] = tatami[h][w + 1] = id
set_tatami.call(h, w + 2, id + 1)
tatami[h][w] = tatami[h][w + 1] = 0
end
if tatami[h + 1][w].zero?
tatami[h][w] = tatami[h + 1][w] = id
set_tatami.call(h, w + 1, id + 1)
tatami[h][w] = tatami[h + 1][w] = 0
end
end
end
end
set_tatami.call(1, 1, 1)
puts str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment