数组包含来自另一个数组的任何值?
什么是最好,最优雅/有效的方法来testing一个数组是否包含第二个数组中的元素?
下面两个例子试图回答这个问题:“食物”包含“奶酪”中的任何元素:
cheeses = %w(chedder stilton brie mozzarella feta haloumi) foods = %w(pizza feta foods bread biscuits yoghurt bacon) puts cheeses.collect{|c| foods.include?(c)}.include?(true) puts (cheeses - foods).size < cheeses.size
(cheeses & foods).empty?
它也是这样做的,它已经发布了injekt,但是它已经用一种语言编译了一些操作。
正如Marc-AndréLafortune在评论中所说的那样,在线性时间内工作,而any?
+ include?
将是二次的。 对于更大的数据集,线性时间会更快。 对于小数据集, any?
+ include?
李贾维斯的答案可能会更快。
您可以检查交叉路口是否为空。
cheeses = %w(chedder stilton brie mozzarella feta haloumi) foods = %w(pizza feta foods bread biscuits yoghurt bacon) foods & cheeses => ["feta"] (foods & cheeses).empty? => false
如何Enumerable#any?
>> cheeses = %w(chedder stilton brie mozzarella feta haloumi) => ["chedder", "stilton", "brie", "mozzarella", "feta", "haloumi"] >> foods = %w(pizza feta foods bread biscuits yoghurt bacon) => ["pizza", "feta", "foods", "bread", "biscuits", "yoghurt", "bacon"] >> foods.any? {|food| cheeses.include?(food) } => true
基准脚本:
require "benchmark" N = 1_000_000 puts "ruby version: #{RUBY_VERSION}" CHEESES = %w(chedder stilton brie mozzarella feta haloumi).freeze FOODS = %w(pizza feta foods bread biscuits yoghurt bacon).freeze Benchmark.bm(15) do |b| b.report("&, empty?") { N.times { (FOODS & CHEESES).empty? } } b.report("any?, include?") { N.times { FOODS.any? {|food| CHEESES.include?(food) } } } end
结果:
ruby version: 2.1.9 user system total real &, empty? 1.170000 0.000000 1.170000 ( 1.172507) any?, include? 0.660000 0.000000 0.660000 ( 0.666015)
Set.new(cheeses).disjoint? Set.new(foods)