Page 2 of 2

Re: A Challenge

Posted: Fri Feb 10, 2012 10:46 am
by spacebiscuit
Which I make....

hello
ello.h
lloh.e
lohe.l
ohel.l
hell.o
=hello

I just cannot see where the reversal occurs...

Re: A Challenge

Posted: Fri Feb 10, 2012 10:57 am
by Celauran
spacebiscuit wrote:Which I make....

Code: Select all

hello
ello.h
lloh.e
lohe.l
ohel.l
hell.o
=hello
That's not quite right. reverse('hello') returns: reverse('ello') with 'h' appended to the end.
reverse('ello') rerturns: reverse('llo') with 'e' appended to the end.
Using simple substitution, we can see that reverse('hello') returns reverse('llo') with e appended to the end, with h appended to the end of that.

Re: A Challenge

Posted: Fri Feb 10, 2012 11:04 am
by spacebiscuit
Thanks for your patience with me!

I'm not sure how your example differs from mine. You take the first character of the string each time and concatenate it. How does that give you 'olleh'?

Re: A Challenge

Posted: Fri Feb 10, 2012 11:11 am
by Celauran
Recursion is tricky, but once you get it you'll wonder how you ever missed it. Trouble is, I'm not really sure how else to explain it.

You're not simply moving the first character to the end of the string. You're appending it to the end of what is returned by the recursive function call. You really need to work backwards through each iteration.

Re: A Challenge

Posted: Fri Feb 10, 2012 11:27 am
by spacebiscuit
It's weird - I have been coding for about 10 years and I get 'for loops' and nested 'for loops' - I write them in my sleep but I just cannot get this.

I get that the recurssion is occuring within the recurssion to the last recursion will complete before the first which will complete last of all so I'm nearl ythere but can't understand how the string is reversed. Maybe I need to play with the code and get it to do some output to the screen along the way to clear it up in my mind.

Thanks.

Re: A Challenge

Posted: Fri Feb 10, 2012 12:12 pm
by spacebiscuit
I think I just have tp conceed that this is beyond me.

I've output 'string' on each recurssion and I get:

hello
ello
llo
lo
o

hello
ello
llo
lo
o

So it parses the string twice - I just do not get it!

Re: A Challenge

Posted: Fri Feb 10, 2012 6:55 pm
by Eric!
This is a bit of a guess because I don't use recursion often. I think that the php recursion stack for calls is first in and last out (FILO). So you put the h in first it doesn't come out until the last call returns.