IT story

배열에 다른 배열의 값이 포함되어 있습니까?

hot-time 2020. 6. 12. 19:28
반응형

배열에 다른 배열의 값이 포함되어 있습니까?


배열에 두 번째 배열의 요소가 포함되어 있는지 테스트하는 가장 효율적인 방법은 무엇입니까?

아래 질문에 대한 답변을 시도하는 두 가지 예 foods에는 다음과 같은 요소 포함됩니다 cheeses.

cheeses = %w(chedder stilton brie mozzarella feta haloumi reblochon)
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?는 2 차입니다. 더 큰 데이터 세트의 경우 선형 시간이 더 빠릅니다. 작은 데이터 세트의 경우 Lee Jarvis의 답변에 표시된 것처럼 any?+ include?가 더 빠를 수 있습니다.


방법에 대한 Enumerable에서 번호 어떤?

>> 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)

교차점이 비어 있는지 확인할 수 있습니다.

cheeses = %w(chedder stilton brie mozzarella feta haloumi)
foods = %w(pizza feta foods bread biscuits yoghurt bacon)
foods & cheeses
=> ["feta"] 
(foods & cheeses).empty?
=> false

Set.new(cheeses).disjoint? Set.new(foods)

참고 URL : https://stackoverflow.com/questions/3941945/array-include-any-value-from-another-array

반응형