【问题标题】:Remove pair duplicates from array of values从值数组中删除对重复项
【发布时间】:2017-08-11 23:52:50
【问题描述】:

问题

lua 中,我有一个值数组(特别是xy 位置值),我想从中删除重复的。数组如下所示:

array = {x1, y1, x2, y2, x3, y3, ... , xn, yn}

其中 n 是坐标对的数量。因此,一个值是x 坐标还是y 坐标完全取决于它在数组中的位置。重复项定义为xa == xb and ya == yb。例如,如果x1 == x2y1 == y2 我想从数组中删除x1y1 或(不是两者) x2y2

问题

  1. 如何从此类数组中删除重复项?
  2. 可以不细分数组吗?
  3. 奖励: 在更一般的情况下,如果数组包含 3 个(甚至更多)变量,即array = {x1, y1, z1, x2, y2, z2, ... , xn, yn, zn}

数值示例

如果给定一个值数组:

array = {1, 1, 2, 1, 1, 1, 2, 1}

那么删除重复项应该会产生一个数组:

array = {1, 1, 2, 1}

【问题讨论】:

  • 到目前为止您尝试过什么?您希望我们为您编写代码吗?

标签: arrays lua duplicates


【解决方案1】:

这一点还涵盖了关于能够处理任何大小的分组变量的第三点。您所要做的就是给出您想要假设的分组大小(默认为 2)

function remove_dups(t,size)
  size = size or 2            --default group size is 2
  assert(#t % size == 0,'Table size is not a multiple of "size"')
  local temp = {}
  local key
  local i = 1
  while i <= #t do
    key = t[i]
    for count = 1, size-1 do
      key = key .. '|' .. t[i+count]
    end
    if temp[key] then
      for count = 1, size do
        table.remove(t,i)
      end
    else
      temp[key] = true
      i = i + size
    end
  end
  return t
end

-- Test the above --

function pa(t,size) -- print array grouped by size
  size = size or 2
  for i,v in ipairs(t) do io.write(v,i ~= #t and i % size == 0 and ', ' or ' ') end
  print()
end

array = {1, 1, 2, 1, 2, 1, 2, 1, 3, 2, 2, 1, 1, 1, 1, 1, 3, 2, 1, 1}

print 'Original'
pa(array)

print 'Dups removed'
pa(remove_dups(array))

【讨论】:

    【解决方案2】:

    您可以使用表格来跟踪重复项。外部表由 x 分量索引,内部表由 y 分量索引。然后,您只需以 2 的增量迭代原始数组,并且仅在元素未被跟踪为重复项时将元素复制到结果中。

    【讨论】:

      【解决方案3】:

      如果对的顺序不重要,那么您可以这样做:

      local Coords = {1, 1, 2, 1, 1, 1, 2, 1}
      local Result,  interim = {}, {}
      
      for i=1,#Coords,2 do
            if Coords[i+1]  then
                 local PointSignature = Coords[i] .. '_' .. Coords[i+1] 
                 interim[PointSignature] = true
            end
      end
      for k,v in pairs(interim) do
           local x, y = k:match("(.+)_(.+)")
           Result[#Result+1] = x
           Result[#Result+1] = y
      end
      for i=1, #Result do
        print(Result[i])
      end
      

      结果稍微排序。

      不同版本,结果按原顺序:

      local Coords = {1, 1, 22, 1, 1, 1, 2, 1, 11, 11, 22, 1}
      local Result,  interim = {}, {}
      
      for i=1,#Coords,2 do
            if Coords[i+1]  then
                 local PointSignature = Coords[i] .. '_' .. Coords[i+1] 
                 if not interim[PointSignature] then
                       Result[#Result+1] = Coords[i]
                       Result[#Result+1] = Coords[i+1] 
                       interim[PointSignature] = true
                 end
            end
      end
      

      【讨论】:

        猜你喜欢
        • 2017-04-10
        • 2016-03-12
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多