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

问题描述 投票:0回答:2

我有一张桌子,如:

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

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

lua lua-table
2个回答
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

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
© www.soinside.com 2019 - 2024. All rights reserved.