如何检查多个Lua表是否包含公共值?

时间:2019-03-17 10:33:46

标签: lua lua-table

我有一张桌子,例如:

local someTable = {       idsA = {1,2,3,4},       idsB = {4,5,6,7},       idsC = {4,8,9,10}     }

并且需要检查所有子表中是否存在一个公共值(在这种情况下-4)。

2 个答案:

答案 0 :(得分:0)

看起来您实际上是将任意数量的表交叉在一起。我敢肯定有库可以做到这一点,但这是一个幼稚的实现:

local idTables = {
  ["idsA"] = {1, 2, 3, 4},
  ["idsB"] = {4, 5, 6, 7},
  ["idsC"] = {4, 8, 9, 10}
}

local intersection = {}
local firstTable = true
for key, tbl in pairs(idTables) do
  -- If this is the first table we are looking at, populate
  -- our intersection table as a map, mapping every ID that appears to a flag.
  -- Note that the choice of flag being a bool is somewhat arbitrary
  if firstTable then
    for _, v in ipairs(tbl) do
      intersection[v] = true
    end
    firstTable = false
  else
    -- Otherwise, we already have a table to intersect against, so for every 
    -- ID in our intersection map, lets check this next table, to see if 
    -- every element of this next table against our intersection map
    for knownId,_ in pairs(intersection) do
      local newTableHasKnownId = false
      for _,id in ipairs(tbl) do
        if id == knownId then
          -- This new table of IDs we're iterating does have the current ID of
          -- the intersection table we're looking at. We can flag it as such, and stop
          -- looking for that known ID
          newTableHasKnownId = true
          break
        end
      end
      -- Drop the 'known' ID from the intersection map if it wasn't in the table
      -- we just iterated.
      if not newTableHasKnownId then
        intersection[knownId] = nil
      end
    end
   end
end

print('intersection results:')
for key,_ in pairs(intersection) do
  print(key)
end

答案 1 :(得分:0)

找到所有通用索引是一个简单的交集:

t={a={1,2,3},
   b={2,6},
   c={2,4,5}}

function intersect(m,n)
 local r={}
 for x in all(m) do
  for y in all(n) do
   if (x==y) then
    add(r,x)
    break
   end
  end
 end
 return r
end

function common_idx(t)
 local r=nil
 for k,v in pairs(t) do
  if not r then
   r=intersect(v,v)
  else
   r=intersect(r,v)
  end
 end
 return r
end

-- 2
for k,v in pairs(common_idx(t)) do
 print(v)
end