, , DigitalRoss, O (n ^ 2). , eql? , ==, , O (n + m):
array1 = [obj1, obj2, obj3, obj4]
array2 = [obj1, obj2, obj5, obj6]
index = {}
found = []
array1.each do |item1| index[item1.first(2)] = item1 end
array2.each do |item2|
item1 = index[item2.first(2)]
found << [item1,item2] if item1 then
end
found.each do |item1, item2| puts "do something" end
, 1 array1. , :
array1 = [obj1, obj2, obj3, obj4]
array2 = [obj1, obj2, obj5, obj6]
index = {}
found = []
array1.each do |item1|
key = item1.first(2)
index[key] ||= []
index[key] << item1
end
array2.each do |item2|
items_from_1 = index[item2.first(2)]
if items_from_1 then
found.concat(items_from_1.map { |item1| [item1,item2] })
end
end
found.each do |item1, item2| puts "do something" end
, .
, .