On Sun, Oct 18, 2009 at 11:43 AM, Toi Toi <toi / mailinator.com> wrote:
> How can one have a function that uses a dynamic amount of each
> statements? Below is the code for level 3. Is there a way to define this
> easily using recursion? I want to avoid having a separate function for
> each level.
>
> def calc nums, level
>  tmp = []
>  nums.each{ |n| tmp.push n
>    nums.each{ |n2| tmp.push n+n2
>      nums.each{ |n3| tmp.push n+n2+n3
>      }}}
>  tmp
> end
>
> puts calc(["0", "1"], 3)
> --

Does this give you the right output?
No recursion, but...

def calc(n, v)
  h,t = Hash[*(0...n.size).zip(n).flatten],[]
  (1..v).each{|x| (0...n.size**x).each{|y| t << y.to_s(n.size).rjust(x,"0")}}
  t.map{|a| a.split(//).map{|b| h[b.to_i]}.join}.sort
end

p calc(["0","1"], 3)


Harry

-- 
A Look into Japanese Ruby List in English
http://www.kakueki.com/ruby/list.html