[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: A question about recursive programming

Kroeger, Simon (ext)

12/12/2005 3:43:00 PM



> From: Hank Gong [mailto:hankgong@gmail.com]
>
> 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=arr if arr.length==1
> temp=arr.delete_at(arr.length-1)
> b=all_sum(arr)+all_sum(arr).collect{|i| i+temp}
> end
>
> c=[1,2]
> p all_sum(c)
>
> Error: in `all_sum': stack level too deep (SystemStackError)
>
> Can anyone give me some advice?

Hmm,

the b= lines doesn't make much sense, you may want to replace
them with return statemants.

Note that delete_at modifies the receiver - the original array
(for this and all other recursions). So it won't work even if
you change the b= to return.

cheers

Simon