On Oct 31, 2011, at 11:11 PM, DamiáÏ M. GonzáÍez wrote:

> Hello friends, my mind is blowing up in flames. I can't understand how
> recursion works in this certainly case( this is part of 'Learn to
> program' of Chris Pine ):
> 
> 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)
> #result is 32
> 
> I can't figure out how the program "counts" the M's, can't understand
> in what part size = size + a_number( guess it must be 1(?). I guess this
> is not easy to explain, by the way if you can give me a hand I'll take
> it! Thanks for your time.

Where recursion is concerned, it's often best to use the debugger and begin stepping through the code until the pattern becomes clear. In your case, an even better way may be to visualize your map at every step. If you run the code with minor adjustments you can create a nice output at ever step. For example:

Looking at tile (5,5)
oooooMooooo
ooooMMooooo
oooooMooMMo
oooMoMoooMo
oooooMMoooo
ooooMMMMooo
MMMMMMMMMMM
oooMMoMMMoo
ooooooMMooo
oMoooMMoooo
oooooMooooo


Looking at tile (4,4)
oooooMooooo
ooooMMooooo
oooooMooMMo
oooMoMoooMo
oooooMMoooo
ooooMXMMooo
MMMMMMMMMMM
oooMMoMMMoo
ooooooMMooo
oMoooMMoooo
oooooMooooo


Looking at tile (5,4)
oooooMooooo
ooooMMooooo
oooooMooMMo
oooMoMoooMo
oooooMMoooo
ooooMXMMooo
MMMMMMMMMMM
oooMMoMMMoo
ooooooMMooo
oMoooMMoooo
oooooMooooo

. . . and so on. I've pasted the code you can run to produce the output here:

https://gist.github.com/1329348

Hope that helps!

Sylvester