遍历集合并删除途中的事物

时间:2019-05-14 10:53:03

标签: loops for-loop julia

我想遍历一个集合并找到第一对匹配的元素,但是我目前的方法一直在使索引一直越界越麻烦。

这是一个简化的MWE示例:

function processstuff(stuff)
    for pointer1 in 1:length(stuff)
        for pointer2 in pointer1:length(stuff)
            println("$(stuff)")
            pointer1 == pointer2 && continue
            if stuff[pointer1] == stuff[pointer2]
                # items match, remove them
                deleteat!(stuff, pointer1)
                deleteat!(stuff, pointer2)
            end
        end
    end
end

processstuff(collect(rand(1:5, 20)))

[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[1, 4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 2, 1, 2, 4, 3, 2, 1, 1]
[4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 1, 2, 4, 3, 2, 1, 1]
[4, 3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 1, 2, 4, 3, 2, 1, 1]
[3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 1, 2, 4, 2, 1, 1]
[3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 1, 2, 4, 2, 1, 1]
[3, 3, 2, 4, 5, 2, 2, 2, 3, 1, 1, 2, 4, 2, 1, 1]
ERROR: LoadError: BoundsError: attempt to access 16-element Array{Int64,1} at index [17]

(显然,此示例只是比较两个数字,不是真正的比较。)

通过删除已处理的两个元素来更新资料集合的想法看起来是可行的,因为我认为Julia每次都会更新迭代内容。但是只有一段时间...?

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法(假设要删除对):

function processstuff!(stuff)
    pointer1 = 1
    while pointer1 < length(stuff)
        for pointer2 in pointer1+1:length(stuff)
            if stuff[pointer1] == stuff[pointer2]
                deleteat!(stuff, (pointer1, pointer2))
                pointer1 -= 1 # correct pointer location as we later add 1 to it
                break
            end
        end
        pointer1 += 1
    end
end

您的代码中存在几个问题:

  • 您两次致电deleteat!,这可能会使索引无效
  • 您的内部循环尝试多次删除pointer1
  • 在外循环中,我使用while动态跟踪stuff的变化大小