From: sanha lee Date: 2005-12-13T01:46:24+09:00 Subject: Re: A question about recursive programming ------=_Part_15423_18708948.1134405977529 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline def all_sum(arr) > return arr if arr.length =3D=3D 1 > temp =3D 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 =3D=3D 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 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 =3D=3D 1 > > temp =3D 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]) > =3D> [5, 6, 7, 4, 5, 3] > > > David > > -- > David A. Black > dblack@wobblini.net > > "Ruby for Rails", forthcoming from Manning Publications, April 2006! > > ------=_Part_15423_18708948.1134405977529--