Determine if one array contains all elements of another array

前端 未结 8 1871
闹比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条回答
  •  -上瘾入骨i
    2021-02-07 12:21

    Counting the number of occurrences and comparing them seems to be the obvious way to go.

    class Array
       def contains_all? arr
           h = self.inject(Hash.new(0)) {|h, i| h[i] += 1; h}
           arr.each do |i|
               return false unless h.has_key?(i)
               return false if h[i] == 0
               h[i] -= 1
           end
           true
       end
    end
    

提交回复
热议问题