In Chris P.'s book, he explains recursion into a bit of detail using
an example in a game he was a part of its making. The explanation he
used was to count the number of tiles there are in a “continent”. I’ll
put the code here and then ask my question after.
These are just to make the map
easier for me to read. “M” is
visually more dense than “o”.
M = ’ land’
o = ’ water’
world = [[o,o,o,o,o,o,o,o,o,o,o],
[o,o,o,o,M,M,o,o,o,o,o],
[o,o,o,o,o,o,o,o,M,M,o],
[o,o,o,M,o,o,o,o,o,M,o],
[o,o,o,M,o,M,M,o,o,o,o],
[o,o,o,o,M,M,M,M,o,o,o],
[o,o,o,M,M,M,M,M,M,M,o],
[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,o,o,o,o,o],
[o,o,o,o,o,o,o,o,o,o,o]]
def continent_size world, x, y
if world[y][x] != ’ land’
Either it’ s water or we already
counted it, but either way, we don’ t
want to count it now.
return 0
end
So first we count this tile…
size = 1
world[y][x] = ’ counted land’
…then we count all of the
neighboring eight tiles (and,
of course, their neighbors by
way of the recursion).
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)
my question: doesn’t world[5][5] mean to compute the whole 5th array of
“world” by the 5th array of “world”, or if we had world[3][8], to
compute
the whole of the 3rd array of “world” by the 8th array of “world”? but
according to this code, the program computes for the actual objects ‘o’
and ‘M’ and not the arrays. aren’t the arrays objects in this case? what
am I missing and what should I know?