2011-02-16 2 views
24

내가 두 배열이 일치하는 두 배열을 비교하고, 일치하는 인스턴스의 수를 계산 :루비 :

@array1 = [a,b,c,d,e] 
@array2 = [d,e,f,g,h] 

내가 일치 (D, E)를 찾기 위해 두 개의 배열을 비교의 수를 계산하려면 일치하는 항목이 발견되었습니다 (2)? 사전에

<% if @array2.include?(@array1) %> 
    # yes, but how to count instances? 
<% else %> 
    no matches found... 
<% end %> 

감사합니다 ~

답변

61

당신은 배열 교차하여이 작업을 수행 할 수 있습니다

@array1 = ['a', 'b', 'c', 'd', 'e'] 
@array2 = ['d', 'e', 'f', 'g', 'h'] 
@intersection = @array1 & @array2 

@intersection 이제 [ 'D', 'E']이어야한다. 그런 다음 다음을 수행 할 수

<% if [email protected]? %> 
    <%= @intersection.size %> Matches Found. 
<% else %> 
    No Matches Found. 
<% end %> 
+1

이렇게하면 중복을 제거 할 수 있습니다. – Trip

0
class Array 
    def dup_hash 
    inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select { 
     |k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r } 
    end 
end 

먼저 당신은 단지 두 배열

@array_sum = @array1 + @array2 

output = [a,b,c,d,e,d,e,f,g,h] 

@array_sum.dub_hash => {d => 2, e => 2} 

를 추가 또는 스토리지간에 총 경기 수를 찾으려면이 How to count duplicates in Ruby Arrays

+0

두 개 이상의 배열이있는 경우 유용합니다. – kriysna

0

를 확인을 추가, 그들을 함께 모은 다음, 고유 한 집합을 뺍니다. 슈퍼 세트 배열의 길이와 uniq 세트의 길이의 차이는 첫 번째 배열의 두 번째 배열과 일치하는 개수입니다. 이 방법은 a2가 고유 집합 인 경우에 가장 효과적입니다.

a1 = ['a','b','c','d','d','d'] 
a2 = ['a','d'] 

superset = (a1 + a2) 
subset = superset.uniq 

matches = superset.count - subset.count