在ruby中使用类似的if条件减少重复

时间:2015-04-18 20:40:59

标签: ruby

实现像迷宫问题一样的递归函数。我将尝试向4个方向移动,每个步骤看起来都非常相似。

if current_y+1<@y_length and @map[current_y+1][current_x].undected?
    path.push current_point
    next_point=  @map[current_y+1][current_x]       
    flag=DFS(next_point,target_point,path)
    if flag=='found'
        return flag
    end
end
if current_y-1>=0 and @map[current_y-1][current_x].undected?
    path.push current_point
    next_point= @map[current_y-1][current_x]
    flag=DFS(next_point,target_point,path)
    if flag=='found'
        return flag
    end
end
if current_x+1<@x_length and @map[current_y][current_x+1].undected?
    path.push current_point
    next_point=@map[current_y][current_x+1]
    flag=DFS(next_point,target_point,path)
    if flag=='found'
        return flag
    end
end
if current_x-1>=0 and @map[current_y][current_x-1].undected?
    path.push current_point
    next_point=@map[current_y][current_x-1]
    flag=DFS(next_point,target_point,path)
    if flag=='found'
        return flag
    end
end

如何让它尽可能短?

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

path.push current_point
if current_y+1<@y_length && @map[current_y+1][current_x].undected?
  next_point=  @map[current_y+1][current_x]
elsif current_y-1>=0 and @map[current_y-1][current_x].undected?
  next_point= @map[current_y-1][current_x]
elsif current_x+1<@x_length and @map[current_y][current_x+1].undected?
  next_point=@map[current_y][current_x+1]
elsif current_x-1>=0 and @map[current_y][current_x-1].undected?
  next_point=@map[current_y][current_x-1]
end
flag=DFS(next_point,target_point,path)
if flag=='found'
  return flag
end

答案 1 :(得分:0)

包含每个语句的简单列表不起作用?

    directions = [
    [current_y+1<@y_length,current_y+1,current_x],
    [current_y-1>=0, current_y-1, current_x],
    [current_x+1<@x_length,current_y, current_x+1],
    [current_x-1>=0,current_x-1]
]

directions.each do |check_condition, y, x|

  next if @map[y][x].undected?
  next if check_condition

  path.push(current_point)
  next_point=@map[y][x]
  flag=DFS(next_point,target_point,path)

  return flag if flag=='found'

end