确定一个数组是否包含另一个数组的所有元素

Chr*_*ris 11 ruby arrays

我需要告诉一个数组是否包含具有重复项的另一个数组的所有元素.

[1,2,3].contains_all? [1,2]   #=> true
[1,2,3].contains_all? [1,2,2] #=> false (this is where (a1-a2).empty? fails)
[2,1,2,3].contains_all? [1,2,2] #=> true
Run Code Online (Sandbox Code Playgroud)

因此第一个数组必须包含第二个数组中每个唯一元素的数量或相等数量.

对于那些使用数组作为集合的人来说,这个问题可以解决它,但是我需要控制重复数据.

更新:基准

在Ruby 1.9.3p194上

def bench
  puts Benchmark.measure {
    10000.times do
      [1,2,3].contains_all? [1,2]
      [1,2,3].contains_all? [1,2,2]
      [2,1,2,3].contains_all? [1,2,2]
    end
  }
end
Run Code Online (Sandbox Code Playgroud)

结果是:

Rohit   0.100000   0.000000   0.100000 (  0.104486)
Chris   0.040000   0.000000   0.040000 (  0.040178)
Sergio  0.160000   0.020000   0.180000 (  0.173940)
sawa    0.030000   0.000000   0.030000 (  0.032393)
Run Code Online (Sandbox Code Playgroud)

更新2:更大的阵列

@a1 = (1..10000).to_a
@a2 = (1..1000).to_a
@a3 = (1..2000).to_a

def bench
  puts Benchmark.measure {
    1000.times do
      @a1.contains_all? @a2
      @a1.contains_all? @a3
      @a3.contains_all? @a2
    end
  }
end
Run Code Online (Sandbox Code Playgroud)

结果是:

Rohit    9.750000   0.410000  10.160000 ( 10.158182)
Chris   10.250000   0.180000  10.430000 ( 10.433797)
Sergio  14.570000   0.070000  14.640000 ( 14.637870)
sawa     3.460000   0.020000   3.480000 (  3.475513)
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 6

class Array
  def contains_all? other
    other = other.dup
    each{|e| if i = other.index(e) then other.delete_at(i) end}
    other.empty?
  end
end
Run Code Online (Sandbox Code Playgroud)