Many nested `for` cycles depending on a variable

2019-07-19 03:33发布

问题:

I want to put as many for cycles in themselfs depending of value in a variable.
For example, if the variable @var = 1, I need to perform:

for letter1 in @range
  do something
end

If the variable @var = 2:

for letter1 in @range
  for letter2 in @range
    do something
  end
end 

If the variable @var = 3

for letter1 in @range
  for letter2 in @range
    for letter3 in @range
      do something
    end
  end
end 

Is there a smarter/less code way than this code below? I don't wanna repeat myself all over again.

if @var == 1
  for letter2 in @range
    do something
  end
elsif @var == 2
  for letter1 in @range
    for letter2 in @range
      do something
    end
  end
elsif @var == 3
  for letter1 in @range
    for letter2 in @range
      for letter3 in @range
        do something
      end
    end
  end 
end

That do something part is always the same in each case. The difference is only how much cycles it is in.

回答1:

You should read about recursion: http://en.wikipedia.org/wiki/Recursion_(computer_science)
It is something like:

def f(depth,letters=[])
  if depth == 0
    do someting with letters
  else
    for letter in @range
      f(depth-1,letters+[letter])
    end
  end
end

f(@var)

f is a function, which goes through letter calling itself again recursively. Each call have info depth, which means, how more deep recursion should be.



回答2:

@range.map{|x| x}.product(*([@range.map{|x| x}] * n)) do |*args|
  do_something_with(*args)
end