开发者

Many nested `for` cycles depending on a variable

开发者 https://www.devze.com 2023-02-06 09:37 出处:网络
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:

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开发者_如何学Python in.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消