Check if an array is subset of another array in Ruby

后端 未结 4 440
遥遥无期
遥遥无期 2020-12-10 10:44

How can I check whether one array is a subset of another array, regardless of the order of elements?

a1 = [3, 6, 4]
a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

...?

a         


        
相关标签:
4条回答
  • 2020-12-10 10:47

    Use sets. Then you can use set.subset?. Example:

    require 'set'
    
    a1 = Set[3,6,4]
    a2 = Set[1,2,3,4,5,6,7,8,9]
    
    puts a1.subset?(a2)
    

    Output:

    true
    

    See it working online: ideone

    0 讨论(0)
  • 2020-12-10 10:50

    Easiest may be:

    (a1 - a2).empty?
    
    0 讨论(0)
  • 2020-12-10 10:58

    The data structure you already have is perfect, just check the intersection:

    (a1 & a2) == a1
    

    Update: The comment discussing permutations is interesting and creative, but quite incorrect as the Ruby implementors anticipated this concern and specified that the order of the result is the order of a1. So this does work, and will continue to work in the future. (Arrays are ordered data structures, not sets. You can't just permute the order of an array operation.)

    I do rather like Dave Newton's answer for coolness, but this answer also works, and like Dave's, is also core Ruby.

    0 讨论(0)
  • 2020-12-10 11:11

    Perhaps not fast, but quite readable

    def subset?(a,b)
      a.all? {|x| b.include? x}
    end
    
    0 讨论(0)
提交回复
热议问题