2014-02-10 1 views
0

두 개의 배열을 공통으로 가지고 비교할 수 있고 어떤 중복도 보이지 않게하고 싶습니다.루비는 공통적으로 갖고있는 것의 두 배열을 비교합니다.

array1 = ['1. walking to the park to find some ice cream'] 
array2 = ['2. walking to the park to find ice cream and find more ice cream'] 

샘플 출력 :

walking to the park find ice cream 
+0

이 [기타] (http://stackoverflow.com/a/21688883/2767755) 대답을 받아 , 제 하나는 최악입니다. 나는 이것을 삭제할 것이다. –

답변

1

으로 내가 할 것 :

a = '1. walking to the park to find some ice cream' 
b = '2. walking to the park to find ice cream and find more ice cream' 

match = Regexp.union(a.split(" ")) 
b.scan(match).uniq.join(" ") 
# => "walking to the park find ice cream" 
+0

[other] (http://stackoverflow.com/a/21688883/2767755) 대답을 수락하면 내 것이 최악입니다. 나는 이것을 삭제할 것이다. –

7
  1. 시작 두 개의 문자열로
  2. 이 공간에 둘 분할

,536,913 그들에 배열 교차로를 수행
a = '1. walking to the park to find some ice cream' 
b = '2. walking to the park to find ice cream and find more ice cream' 

a1 = a.split(" ") 
b1 = b.split(" ") 

common = a1 & b1 
#=> ["walking", "to", "the", "park", "find", "ice", "cream"] 

정규식은 더 느립니다. 여기에 배열 조합 및 사용하여 정규 표현식 사이의 빠른 비교는 다음과 같습니다

require 'benchmark' 

def arr_only(a,b) 
    a1 = a.split(" ") 
    b1 = b.split(" ") 
    a1 & b1 
end 

def w_regex(a,b) 
    match = Regexp.union(a.split(" ")) 
    b.scan(match).uniq 
end 

n = 100_000 
Benchmark.bm do |x| 
    x.report("arr:") { n.times {|i| arr_only(a, b) } } 
    x.report("regex:"){ n.times {|i| w_regex(a, b) } } 
end 

#     user  system  total  real 
# arr:   1.030000 0.000000 1.030000 ( 1.031033) 
# regex:  4.970000 0.010000 4.980000 ( 4.993263)