Ruby 在网格上查找匹配行的递归方法
我有一个网格对象,由空间对象填充,每个对象都包含一个值。我要做的是写一个方法,它取一个空格,一个表示我想要找到的相等空格数量的数字,看看网格上是否有x个相等空格在同一方向 在psuedo代码中,我计划的步骤是:Ruby 在网格上查找匹配行的递归方法,ruby,recursion,Ruby,Recursion,我有一个网格对象,由空间对象填充,每个对象都包含一个值。我要做的是写一个方法,它取一个空格,一个表示我想要找到的相等空格数量的数字,看看网格上是否有x个相等空格在同一方向 在psuedo代码中,我计划的步骤是: 从网格的左上角开始 检查每个方向(N、S、E、W、NE、NW、SE、SW)有无2种情况 那个方向的空间是存在的 该空间中的值与当前空间中的值匹配 如果这些条件都失败了,我想再次调用该方法,但将当前空间作为下一个空间(增加左>>右>>上>>下) 如果满足这些条件,我希望将该值存储在一个列
def check_for_row_of(num)
found = nil
each_space do |space|
COMPASS.each do |direction|
if num_spaces_in_direction(space.pos, direction) == num
values = get_spaces_by_pattern(space.pos, direction)
found = values.uniq[0] if values.uniq.length == 1 && values.uniq[0] != " "
end
end
end
found
end
如果我理解正确,我相信下面的代码回答了您的问题。请告诉我这是否和你想的不太一样 为了便于阅读,我将递归
search
函数与遍历每个单元格和方向的(有些笨拙)逻辑分开
另外,值得一提的是,我正在对数组数组调用转置
和反转
,以便人们更容易阅读网格。左下角是(0,0),右上角是(2,2)
如果你提供一个小例子,包括期望的结果,你会产生更多的兴趣。谢谢你,我接受了你的建议
def search(grid, x, y, direction, length_to_find, value_to_find=nil)
return true if length_to_find == 0
value_at_location = grid.transpose[x].reverse[y] if grid.transpose[x]
value_to_find ||= value_at_location
return false if value_at_location != value_to_find
y += 1 if direction =~ /N/i
y -= 1 if direction =~ /S/i
x += 1 if direction =~ /E/i
x -= 1 if direction =~ /W/i
search(grid, x, y, direction, length_to_find - 1, value_to_find)
end
def row_of?(grid, length_to_find)
grid.length.times do |row|
grid[0].length.times do |col|
%w[N NE E SE S SW W NW].each do |direction|
if search(grid, row, col, direction, length_to_find)
return true
end
end
end
end
false
end
grid = [
[ "O", "O", "O"],
[ " ", "O", "X"],
[ " ", "X", "X"]
]
puts row_of?(grid, 3)