gpt4 book ai didi

ruby - 在 ruby​​ 中创建任意深度的嵌套循环

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:05 26 4
gpt4 key购买 nike

我想编写一个 ruby​​ 程序,它可以跨越任意维数的空间。

在 3 个维度上,我正在做的事情看起来像这样:

x_range = (-1..1)
y_range = (-1..1)
z_range = (-1..1)

step_size = 0.01

x_range.step(step_size) do |x|
y_range.step(step_size) do |y|
z_range.step(step_size) do |z|

# do something with the point x,y,z

end
end
end

我想对 n 个维度做同样的事情

最佳答案

这是我想到的第一件事:

def enumerate(nDimens, bottom, top, step_size)
bottom = (bottom / step_size).to_i
top = (top / step_size).to_i

range = (bottom..top).to_a.map{ |x| x * step_size }
return range.repeated_permutation(nDimens)
end

stepper = enumerate(4, -1, 1, 0.1)

loop do
puts "#{stepper.next()}"
end

这会产生:

[-1.0, -1.0, -1.0, -1.0]
[-1.0, -1.0, -1.0, -0.9]
[-1.0, -1.0, -1.0, -0.8]
# Lots more...
[1.0, 1.0, 1.0, 0.8]
[1.0, 1.0, 1.0, 0.9]
[1.0, 1.0, 1.0, 1.0]

这假设所有维度都具有相同的范围,但如果由于某种原因不成立,则很容易调整。

关于ruby - 在 ruby​​ 中创建任意深度的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11822464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com