sanha lee
12/12/2005 4:46:00 PM
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.
On 12/12/05, dblack@wobblini.net <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!
>
>