2016-12-13 72 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