From: dblack@... Date: 2005-12-13T01:56:29+09:00 Subject: Re: A question about recursive programming Hi -- On Tue, 13 Dec 2005, sanha lee wrote: > def all_sum(arr) >> return arr if arr.length == 1 >> temp = arr[-1] > # sorry about this, it should be return all_sum(arr[0...-1]) + > all_sum(arr[0...-1]).collect ..... > # not all_sum(arr[1...-1]).collect. >> return all_sum(arr[0...-1]) + all_sum(arr[1...-1]).collect {|i| i + temp} >> end > > except that mistake, I can not see any difference between your code and > mine, > except that your code doesn't deal with the case where arr.length == 1. > my result of all_sum([1, 2, 3, 4]) is this [1, 2, 3, 4, 6, 5, 7, 8, 10] > sorry if i am wrong, no offence. I'm probably misunderstanding what the original poster wanted. I dropped the length == 1 case since in [1,2,3,4], 1 is not the sum of any two elements. I was basically doing: 1 + 2 1 + 3 1 + 4 2 + 3 2 + 4 3 + 4 David > > > > > On 12/12/05, dblack@wobblini.net wrote: >> >> Hi -- >> >> On Tue, 13 Dec 2005, sanha lee wrote: >> >>> I think that it is better solution >>> >>> def all_sum(arr) >>> return arr if arr.length == 1 >>> temp = arr[-1] >>> return all_sum(arr[0...-1]) + all_sum(arr[1...-1]).collect {|i| i + >> temp} >>> end >> >> I get a too-deep recursion with that too. Here's another candidate: >> >> def all_sum(arr) >> case arr.size >> when 1 then [] >> else arr[0..-2].map {|i| i + arr[-1]} + all_sum(arr[0..-2]) >> end >> end >> >> p all_sum([1,2,3,4]) >> => [5, 6, 7, 4, 5, 3] >> >> >> David >> >> -- >> David A. Black >> dblack@wobblini.net >> >> "Ruby for Rails", forthcoming from Manning Publications, April 2006! >> >> > -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!