Как проверить, содержат ли несколько таблиц Lua общие значения? - PullRequest
0 голосов
/ 17 марта 2019

У меня есть таблица таблиц, таких как:

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

И нужно проверить, существует ли общее значение, которое существует во всех вложенных таблицах (в этом случае - 4).

Ответы [ 2 ]

0 голосов
/ 18 марта 2019

Это прямое пересечение, чтобы найти все общие индексы:

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 голосов
/ 18 марта 2019

Похоже, вы по существу пересекаете любое количество таблиц вместе.Я уверен, что есть библиотеки для этого, но вот наивная реализация:

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