Determine if one array contains all elements of another array

前端 未结 8 1872
闹比i
闹比i 2021-02-07 12:05

I need to tell if an array contains all of the elements of another array with duplicates.

[1,2,3].contains_all? [1,2]   #=> true
[1,2,3].contains_all         


        
8条回答
  •  情深已故
    2021-02-07 12:26

    class Array
      def contains_all?(ary)
        ary.uniq.all? { |x| count(x) >= ary.count(x) }
      end
    end
    

    test

    irb(main):131:0> %w[a b c c].contains_all? %w[a b c]
    => true
    irb(main):132:0> %w[a b c c].contains_all? %w[a b c c]
    => true
    irb(main):133:0> %w[a b c c].contains_all? %w[a b c c c]
    => false
    irb(main):134:0> %w[a b c c].contains_all? %w[a]
    => true
    irb(main):135:0> %w[a b c c].contains_all? %w[x]
    => false
    irb(main):136:0> %w[a b c c].contains_all? %w[]
    => true
    

    The following version is faster and shorter in code.

    class Array
      def contains_all?(ary)
        ary.all? { |x| count(x) >= ary.count(x) }
      end
    end
    

提交回复
热议问题