在ruby中使用类似的if条件减少重复
当实现像迷宫问题这样的递归函数时。我将尝试移动到4个方向,每一步看起来都很相似在ruby中使用类似的if条件减少重复,ruby,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=='f
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
如何使其尽可能短?您可以尝试以下方法:
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
而一个简单的列表加上一个each语句就行不通了
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
对不起,我忘了强调它是一个递归函数,这意味着每个if分支都必须通过。谢谢,现在我通过将method对象放入数组并通过它来完成它,与您的非常类似。我喜欢你的解决方案: