许多嵌套的“for”循环取决于变量

发布于 2024-10-14 00:03:14 字数 857 浏览 3 评论 0原文

我想根据变量中的值在其自身中放入尽可能多的 for 循环。
例如,如果变量@var = 1,我需要执行:

for letter1 in @range
  do something
end

如果变量@var = 2

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

如果变量@var = 3

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

有没有更聪明的/比下面的代码更少的代码方式?我不想再重复一遍。

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

在每种情况下,“做某事”部分始终是相同的。区别仅在于其周期数。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

本王不退位尔等都是臣 2024-10-21 00:03:14

您应该阅读有关递归的内容: http://en.wikipedia.org/wiki/Recursion_(computer_science )
它类似于:

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 是一个函数,它通过字母再次递归地调用自身。每个调用都有信息深度,这意味着递归应该有多深。

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.

扎心 2024-10-21 00:03:14
@range.map{|x| x}.product(*([@range.map{|x| x}] * n)) do |*args|
  do_something_with(*args)
end
@range.map{|x| x}.product(*([@range.map{|x| x}] * n)) do |*args|
  do_something_with(*args)
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文