2016-12-13 59 views
0

我试图做一个洪水填充,要求用户输入从随机生成的数组中填充数字1-6,由'颜色'表示的右上角开始。我刚刚添加了oldColor/newColor功能,并且收到错误消息,我不确定为什么。除此之外,该算法一直要求输入,而不打印每个步骤中新的填充填充。红宝石递归泛滥 - 它

def floodfill(array_1, row, column, colours, oldColor, newColor) 
      #colours is an array of the 6 colours i'm going to be using 
      boxHeight = array_1.length 
      boxWeight = array_1[0].length 
      oldColor = array_1 
      #puts oldColor 
      print "> " 
      newColor = gets.chomp.downcase 

      if array_1[row][column] != oldColor 
      return 
      if newColor == "r" 
       newColor = colours[:red] 
       array_1[row][column] = newColor 
       floodfill(array_1, row + 1, column, colours, newColor) # right 
       floodfill(array_1, row - 1, column, colours, newColor) # left 
       floodfill(array_1, row, column + 1, colours, newColor) # down 
       floodfill(array_1, row, column - 1, colours, newColor)# up 
       print_it 
      else 
       puts "didnt get that" 
       array_1.each do |row| 
       row.each do |c| 
        print c 
       end 
       puts 
      end 
      end 
     end 
     end 
floodfill(array_1,14,9,colours,0,0) 

我不能直接发表图片,但这里是我的输出现在看起来像,然后失败消息 http://imgur.com/a/88UrK

+0

请阅读“[mcve]”。我们需要显示问题的最小代码和输入数据,以及您的预期输出。你得到什么错误代码?另外,在Ruby中,我们使用snake_case作为变量名称。 camelCaseIsTooHardToRead。 –

+0

这个'oldColor = array_1'没有任何意义。你为什么放弃这个论点,并用图片的副本来替代它? – Max

+0

我的思考过程是让oldColors包含最初那里的内容,然后让newColors承担填充责任。这会不会奏效?我对ruby相当陌生,并希望指出正确的方向来实现这个工作 – LeeKay220

回答

1

这短路您的代码执行:

if array_1[row][column] != oldColor 
    return 

一旦命中return它从该方法返回nil并且不会评估任何其他内容。

boxHeightboxWeight从不初始化,newColorgets覆盖,这可能不应该发生。

最后,代码丢失了尾随end。我建议使用工具自动重新格式化或重新加载代码,这将有助于避免此类问题。

+0

你能进一步解释吗?我将如何去纠正它?我没有得到实施boxHeight和boxWeight,因为我首先想确保递归填充函数适用于至少一种颜色 – LeeKay220

0

红宝石if语句并不像在C或Java工作在那里你可以写类似

if array_1[row][column] != oldColor 
    return 

您也需要一个end或者你需要把如果返回后。

if array_1[row][column] != oldColor 
    return 
end 
# or 
return if array_1[row][column] != oldColor 
+0

因此,做这两个之一会允许它注册更改后退出循环? – LeeKay220