问题描述
我想根据变量中的值在它们自身中放入尽可能多的for
循环.
例如,如果变量@var = 1
,我需要执行:
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
如果变量@var = 2
:
for letter1 in @range
for letter2 in @range
do something
end
end
如果变量@var = 3
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
do something
部分在每种情况下总是相同的.区别仅在于它处于多少个周期.
That do something
part is always the same in each case. The difference is only how much cycles it is in.
推荐答案
您应该阅读有关递归的信息: http://en.wikipedia.org/wiki/Recursion_(computer_science)
就像这样:
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
是一个函数,它通过字母递归再次调用其自身.每个调用都有信息depth
,这意味着应该进行更深层的递归.
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.
这篇关于许多嵌套的"for"循环取决于变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!