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)
> --

I think this will do it if your array size <= 36

def calc_new(arr,l)
  h,t = Hash[*(0...arr.size).zip(arr).flatten],[]
p h
  (1..l).each do |z|
    (0...arr.size**l).each do |x|
      t << x.to_s(arr.size).rjust(z,"0")
    end
  end
  t.uniq.sort.map{|c| c.split(//).map{|d| h[d.to_i(arr.size)]}.join}
end

p calc_new((1..12).to_a, 3)


Harry

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