How to find if an array is subset of another array?

青春壹個敷衍的年華 提交于 2019-12-11 06:59:53

问题


In Python we can use set or itertools to find the subset of one list of another list, how do we do the same in Lua ?

a = {1,2,3}
b = {2,3}

How do i check that b is a subset of a ?


回答1:


Sets can be implemented in Lua using tables as look-ups for membership testing (as done in Programming in Lua). The keys in the table are the elements of the set and the values are either true if the element belongs to the set or nil otherwise.

a = {[1]=true, [2]=true, [3]=true}
b = {[2]=true, [3]=true}

-- Or create a constructor
function set(list)
   local t = {}
   for _, item in pairs(list) do
       t[item] = true
   end
   return t
end

a = set{1, 2, 3}
b = set{2, 3}

Writing set operations is straightforward in this form as well (as here).

function subset(a, b)
   for el, _ in pairs(a) do
      if not b[el] then
         return false
      end
    end
   return true
end

print(subset(b, a)) -- true
print(subset(set{2, 1}, set{2, 2, 3, 1})) -- true

a[1] = nil -- remove 1 from a
print(subset(a, b)) -- true

If a and b must remain in array form then subset can be implemented like so:

function arraysubset(a, b)
   local s = set(b)
   for _, el in pairs(a) -- changed to iterate over values of the table
      if not s[el] then
         return false
      end
   end
   return true
end


来源:https://stackoverflow.com/questions/28294421/how-to-find-if-an-array-is-subset-of-another-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!