I fixed Pine's psych problem using returns, but now he explains recursion. I asked Jameson if methods can call upon other methods today, to which his response was "duh," and then other utterances. Perfect timing while Pine explains methods calling upon themselves. Very useful if I wanted to rewrite my number guess game.
He uses recursion to find the largest continent in a map drawn by grid. Looking over the code I couldn't find the recursion the first time. But wait a second...
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)
There it is!
I got to write all these chapter 10 programs up tonight. I'm falling behind and really don't want blogger to be an excuse.
No comments:
Post a Comment