从值数组中删除成对重复项

3

问题

我在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}
4个回答

2

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


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

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))

0

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

您可以将其转换为地图,然后返回列表:

local map = {}
for i = 1, #array-1, 2 do
    local x, y = array[i], array[i+1]
    if not map[x] then map[x] = {} end
    map[x][y] = true
end

local uniqueList = {}
for x, ys in pairs (map) do
    for y, b in pairs (ys) do
        table.insert(uniqueList, x)
        table.insert(uniqueList, y)
    end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接