从值数组中删除对重复项

时间:2017-03-20 15:48:22

标签: arrays lua duplicates

问题

lua我有一系列值(特别是 - xy位置值),我希望从中删除重复的。该数组如下所示:

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

其中n是corrdinates对的数量。因此,值是x坐标还是y坐标仅由其在数组中的位置决定。副本定义为xa == xb and ya == yb。例如,如果x1 == x2y1 == y2我要删除x1y1 或(不是两者) x2和{来自数组的{1}}。

问题

  1. 如何从这样的数组中删除重复项?
  2. 可以在不细分数组的情况下完成吗?
  3. 奖励:在更一般的情况下,如果数组包含3个(或更多个)变量,即y2
  4. 数字示例

    如果给出了一组值:

    array = {x1, y1, z1, x2, y2, z2, ... , xn, yn, zn}

    然后删除重复项应该会产生一个数组:

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

这个还涵盖了能够处理任何大小的分组变量的第3点。您所要做的就是给出您想要的分组大小(默认为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))
相关问题