From: Hank Gong Date: 2005-12-13T16:39:48+09:00 Subject: Re: A question about recursive programming ------=_Part_2309_18898296.1134459582144 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline concise!!! On 12/13/05, William James wrote: > > Hank Gong wrote: > > I want to calculate all sum possibility of interger array. I know there > are > > other non-recursive way to do it. > > But when I wrote recursive code to achieve it, I just got error. > > > > > > def all_sum(arr) > > b=3Darr if arr.length=3D=3D1 > > temp=3Darr.delete_at(arr.length-1) > > b=3Dall_sum(arr)+all_sum(arr).collect{|i| i+temp} > > end > > > > c=3D[1,2] > > p all_sum(c) > > > > Error: in `all_sum': stack level too deep (SystemStackError) > > > > Can anyone give me some advice? > > > class Array > def add( n ) > self.map{|item| item + n } > end > def tail > self[1..-1] > end > end > > def sums( array ) > return [] if array.size < 2 > array.tail.add( array.first ) + sums( array.tail ) > end > > > ------=_Part_2309_18898296.1134459582144--