Determine if one array contains all elements of another array

前端 未结 8 1885
闹比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:22

    Answering with my own implementation, but definitely want to see if someone can come up with a more efficient way. (I won't accept my own answer)

    class Array
      def contains_all?(a2)
        a2.inject(self.dup) do |copy, el|
          if copy.include? el
            index = copy.index el
            copy.delete_at index
          else
            return false
          end
          copy
        end
        true
      end
    end
    

    And the tests:

    1.9.3p194 :016 > [1,2,3].contains_all? [1,2]   #=> true
     => true 
    1.9.3p194 :017 > [1,2,3].contains_all? [1,2,2] #=> false (this is where (a1-a2).empty? fails)
     => false 
    1.9.3p194 :018 > [2,1,2,3].contains_all? [1,2,2] #=> true
     => true 
    

提交回复
热议问题