【问题标题】:How to check if multiple Lua tables contain common values?如何检查多个 Lua 表是否包含共同值?
【发布时间】:2022-01-06 19:18:48
【问题描述】:

我有一个表格,例如:

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

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

【问题讨论】:

  • 你试过什么?这不是编码服务。您必须遍历您的表格并比较每个条目。你想做什么也很重要。您只是想知道是否有通用 ID,还是想知道哪些 ID 是通用的,或者它们在哪些表中......
  • 你意识到这不是正确的 Lua 语法,对吧?
  • 在您给出的示例中,所有三个表都恰好有 sequences 并且没有其他键。这是结构要求吗?有什么可以依靠的?

标签: lua lua-table


【解决方案1】:

找到所有公共索引是一个简单的交集:

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 2014-04-30
      • 2013-02-08
      • 2011-01-17
      • 1970-01-01
      • 2012-09-17
      • 2018-09-05
      • 2011-10-08
      • 2020-10-08
      相关资源
      最近更新 更多