我一直在嘗試使用Chris Pine的「學習編程」一書學習ruby。在閱讀本書之前,我真的很興奮,直到第10章和使用的例子。現在這一章以及它的例子已經完全縮小了我對繼續這本書的興奮。在這個例子中,我完全不知道它如何計算tile,或者爲什麼當方法用continent_size world,x,y的屬性定義時,他使用world [y],[x]?我不知道這個例子中的遞歸是如何工作的。有人能夠對這個例子進一步闡明作者實際上想要做什麼嗎?Chris Pine Ruby ch 10,遞歸
M = 'land'
o = 'water'
world = [
[o,o,o,o,o,M,o,o,o,o,o],
[o,o,o,o,M,M,o,o,o,o,o],
[o,o,o,o,o,M,o,o,M,M,o],
[o,o,o,M,o,M,o,o,o,M,o],
[o,o,o,o,o,M,M,o,o,o,o],
[o,o,o,o,M,M,M,M,o,o,o],
[M,M,M,M,M,M,M,M,M,M,M],
[o,o,o,M,M,o,M,M,M,o,o],
[o,o,o,o,o,o,M,M,o,o,o],
[o,M,o,o,o,M,M,o,o,o,o],
[o,o,o,o,o,M,o,o,o,o,o]]
def continent_size world, x ,y
if x < 0 or x > 10 or y < 0 or y > 10
return 0
end
if world[y][x] != 'land'
return 0
end
size = 1
world [y][x] = 'counted land'
size = size + continent_size(world, x-1, y-1)
size = size + continent_size(world, x , y-1)
size = size + continent_size(world, x+1, y-1)
size = size + continent_size(world, x-1, y)
size = size + continent_size(world, x+1, y)
size = size + continent_size(world, x-1, y+1)
size = size + continent_size(world, x , y+1)
size = size + continent_size(world, x+1, y+1)
size
end
puts continent_size(world, 5, 5)
這個程序和章節只是沒有點擊。我覺得我掌握了遞歸,但看看這段代碼,感到困惑和沮喪。有人可以通過代碼來引導我並解釋發生了什麼嗎? – Ordep81