对于每个增加数组的循环

[英]for each loop with increase array


I am trying to iterate through an array using a for each loop in ruby but inside of the loop I am increasing the size of the array conditionally. I want to iterate through the array until I have run the iterate with every element in the array including all the ones I have added

我试图使用for ruby​​中的每个循环迭代一个数组,但是在循环内部我有条件地增加了数组的大小。我想迭代数组,直到我用数组中的每个元素运行迭代,包括我添加的所有元素

for x in fol
    t = get_transition(x,"")
    for i in t
        if i != nil && !fol.include?(i)
            fol = fol.push(i)
            fol = fol.flatten
        end
    end
end

In the first loop of this code the array

在这段代码的第一个循环中的数组

fol = [1]

and it adds the element 3 to the array creating

并将元素3添加到数组创建中

fol = [1, 3]

It will then run the loop again with x = 3 and the array becomes

然后它将再次以x = 3运行循环并且数组变为

fol = [1, 3, 2]

But it will not iterate again with x = 2. Thank you in advance for any assistance

但它不会再次使用x = 2进行迭代。请提前感谢您提供任何帮助

For clarification purposes I have added in print statements and the output that they generate.

为了澄清目的,我在print语句中添加了它们生成的输出。

fol.each do |x|
    puts "fol = #{fol}"
    puts "x = #{x}"
    t = get_transition(x,"")
    puts "t = #{t}"
    t.each do |i|
        puts "i = #{i}"
        if i != nil && !fol.include?(i)
            fol = fol.push(i)
            fol = fol.flatten
        end
    end
end

puts "\nfol = #{fol}"

This code generates this output

此代码生成此输出

fol = [1]
x = 1
t = [3]
i = 3
fol = [1, 3]
x = 3
t = [2]
i = 2

fol = [1, 3, 2]

1 个解决方案

#1


3  

I am trying to iterate through an array using a for each loop in ruby but inside of the loop I am increasing the size of the array conditionally. I want to iterate through the array until I have run the iterate with every element in the array including all the ones I have added

我试图使用for ruby​​中的每个循环迭代一个数组,但是在循环内部我有条件地增加了数组的大小。我想迭代数组,直到我用数组中的每个元素运行迭代,包括我添加的所有元素

Why not just treat this as a queue? That's pretty much what you've described

为什么不把它当作队列呢?这就是你所描述的

queue = fol.clone
until queue.empty?
  x = queue.pop
  t = get_transition(x,"")
  for i in t
    if i != nil && !fol.include?(i)
       # Not too sure what type "i" is here, but you push onto the queue here
       # I'd try to avoid flattening if you know what your data types are as it will be slow
    end
  end
end
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/03/04/5c6e184c19ec19588e4cebe43fbe6952.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告