From: Alphonse 23 Date: 2013-06-11T00:47:58+09:00 Subject: Re: Need help understanding recursion. Sorry if this reply is a little late. pedro oliva wrote in post #1111657: > Thanks for the quick replies and all the help. > Tamara and Brandon, Does The Little Schemer apply to Ruby or is it all > Scheme?? The little Schemer only applies to scheme. > example: > #we started with > continent_size(world,5,5) #size=1 here, and now mark this tile as > 'counted tile' > > and continue on to > size = size + continent_size(world, x-1, y-1) # 1(size) + (recursion > call with new parameters to continent_size(world, 4 (5-1), 4 (5-1) > > Now at this point do we run the line of code we just ran with the new > (world 4,4) parameters and continue to recursively run this till we get > to the base case? In essence keep continuing counting the tiles that are > in a down-left direction till we run out of land to count? Or Do we move > on to the next line of code which would be: We continue on in the downward direction till we either run out of land or we find the bounds of the map. That is, the base cases of this recursive method. So, it will continue to build up a stack of calls until it gets a return. > size = size + continent_size(world, x , y-1) > > and pass the (world, 4,4) parameters that we got from the first line of > code, then continuously pass the same parameters all the way down the > rest of the code in the following lines? > > 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) You can test this yourself: def continent_size world, x ,y print "x: " + x + " y:" y if x < 0 or x > 10 or y < 0 or y > 10 puts " return bounds of map." return 0 end if world[y][x] != 'land' puts " return no land found." return 0 end .... And you can see the stack build up as it finds more and more land, until it returns. -- Posted via http://www.ruby-forum.com/.