2014-05-03 89 views
0

下面的代碼應該找到arr_1arr_2中缺少的數字。比較Ruby中陣列的最有效方法

def compare_1 (arr_1, arr_2) 
    output = [] 

    temp = arr_2.each_with_object(Hash.new(0)) { |val, hsh| hsh[val] = 0 } 

    arr_1.each do |element| 
     if !temp.has_key? (element) 
      output << element 
     end 
    end 
    puts output 
end 
def compare_2 (arr_1, arr_2) 
    out = [] 
    arr_1.each do |num| 
     if (!arr_2.include?(num)) 
      out << num 
     end 
    end 
    puts out 
end 

根據'基準',第一種方法更快,大概是通過使用散列。有沒有更好的方法來寫這些或實現這一目標?

compare_1 times: 

    0.000000 0.000000 0.000000 ( 0.003001) 

compare_2 times: 

    0.047000 0.000000 0.047000 ( 0.037002) 
+2

?你可以做'arr1 - arr2' – SteveTurczyn

+1

數組差異:http://www.ruby-doc.org/core-2.1.1/Array.html#2D-method – Micka

+0

'array_1','array_2'在哪裏? – sawa

回答

4

上面的代碼應該找到array_1被 缺少array_2

正如SteveTurczyn說你可以做array_1 - array_2

這裏的數字是Array Difference

定義

返回新的a rray是原始數組的副本,刪除也出現在other_ary中的任何 項目。訂單從 原始數組中保留。

它使用它們的散列和eql比較元素?提高效率的方法。

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ] 

編輯

至於性能,我通過收集該線程的信息做出了benchmark

################################################ 
# $> ruby -v 
# ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin12.0] 
################################################ 
require 'benchmark' 

def compare_1 arr_1, arr_2 
    output = [] 

    temp = arr_2.each_with_object(Hash.new(0)) { |val, hsh| hsh[val] = 0 } 

    arr_1.each do |element| 
     if !temp.has_key? (element) 
      output << element 
     end 
    end 
    output 
end 

def compare_2 arr_1, arr_2 
    out = [] 
    arr_1.each do |num| 
     if (!arr_2.include?(num)) 
      out << num 
     end 
    end 
    out 
end 

require 'set' 
def compare_3 arr_1, arr_2 
    temp = Set.new arr_2 
    arr_1.reject { |e| temp.include? e } 
end 

def native arr_1, arr_2 
    arr_1 - arr_2 
end 




a1 = (0..50000).to_a 
a2 = (0..49999).to_a 
Benchmark.bmbm(11) do |x| 
    x.report("compare_1:") {compare_1(a1, a2)} 
    x.report("compare_2:") {compare_2(a1, a2)} 
    x.report("compare_3:") {compare_3(a1, a2)} 
    x.report("native:") {native(a1, a2)} 
end 
################################################ 
# $> ruby array_difference.rb 
# Rehearsal ----------------------------------------------- 
# compare_1: 0.030000 0.000000 0.030000 ( 0.031663) 
# compare_2: 71.300000 0.040000 71.340000 (71.436027) 
# compare_3: 0.040000 0.000000 0.040000 ( 0.042202) 
# native:  0.030000 0.010000 0.040000 ( 0.030908) 
# ------------------------------------- total: 71.450000sec 
# 
#     user  system  total  real 
# compare_1: 0.030000 0.000000 0.030000 ( 0.030870) 
# compare_2: 71.090000 0.030000 71.120000 (71.221141) 
# compare_3: 0.030000 0.000000 0.030000 ( 0.034612) 
# native:  0.030000 0.000000 0.030000 ( 0.030670) 
################################################