【问题标题】:why is this giving me an infinite loop为什么这给了我一个无限循环
【发布时间】:2015-09-20 03:44:08
【问题描述】:

我不知道为什么它是一个无限循环。我知道当前是 size=1 并且我知道无限循环在 .each 中。

while current!= nil do 
  distance+=1 
  discovered[current] = true
  print move[current].size

  move[current].each{ |coord|
    if discovered[coord] == nil then 
      if paths[distance] == nil then
        paths[distance] = Array.new 
      end 
      paths[distance].push(coord)
      to_visit.push(coord)
    end 
  }

  current = to_visit.delete_at(0)
end

【问题讨论】:

  • 首先将“while current!= nil do”更改为“while current do”,然后将“discovered[coord] == nil”更改为“discovered[coord].nil?”。 TBH 这段代码看起来相当程序化,而不是面向对象的。

标签: ruby infinite-loop


【解决方案1】:

具体不知道move的内容,有点难说。我假设它包含您可以根据当前位置移动到的其他“网格单元”?

如果是这种情况,原因可能是下一个网格单元的move 也引用了当前网格单元。两个网格单元在move 中相互引用就可以无限循环了。

我稍微清理了你的代码。如果这没有帮助,请发布move 的内容以获得更准确的答案。

while current do 
  distance += 1 
  discovered[current] = true

  move[current].each do |coord|
    unless discovered[coord] 
      paths[distance] ||= Array.new  
      paths[distance].push(coord)

      to_visit.push(coord)
    end 
  end

  current = to_visit.delete_at(0)
end

【讨论】:

  • 我正在查看move['(0,3)'],其中包含一个数组[(0,2)],每个循环只是一遍又一遍地重复(0,2)。它不是自引用的。
  • move['(0,2)'] 中有什么内容?
  • {"0,1"=>["0,0", "1,1"], "0,2"=>["1,2", "0,3"] , "0,3"=>["0,2"], "1,0"=>["1,1", "2,0"], "1,1"=>["1,2" , "1,0", "0,1", "2,1"], "1,2"=>["1,1", "2,2", "0,2"], "2, 0"=>["2,1", "1,0"], "2,1"=>["3,1", "1,1", "2,0", "2,2"] , "2,2"=>["2,1", "1,2", "2,3"], "2,3"=>["3,3", "2,2"], " 3,1"=>["2,1", "3,2"], "3,2"=>["3,1"], "3,3"=>["2,3"]}这是每个拥有的坐标和值
  • 问题是0,2 引用了0,3,而0,3 引用了0,2。当你遍历0,2时,0,3被添加到to_visit,当你访问0,3时,0,2被添加,等等,无穷无尽。
  • 为什么在我检查发现时将 0,3 添加到 to_visit
猜你喜欢
  • 1970-01-01
  • 2013-12-13
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2018-01-13
相关资源
最近更新 更多