Search code examples
luamoonscript

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


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 ?


Solution

  • 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