Skip to content

Instantly share code, notes, and snippets.

@nzifnab
Created July 12, 2010 21:33
Show Gist options
  • Save nzifnab/473089 to your computer and use it in GitHub Desktop.
Save nzifnab/473089 to your computer and use it in GitHub Desktop.
class Array
def find_duplicates(other_array)
hsh = {}
other_array.each{|val| hsh[val] = true}
# Ya, could be done easier using Array.select{}, but that feels like cheating
# return test_array.select{|val| hsh[val] == true}
result_array = []
self.each{ |val| result_array << val if hsh[val] }
result_array
end
end
array1 = [2, 8, 3, 4, 42, 58, 7, 83, 34, 72, 22, 47, 28, 92, 51]
array2 = [52, 59, 83, 34, 2, 76, 99, 48, 42, 4]
if (result1 = array1.find_duplicates(array2)) == [2, 4, 42, 83, 34]
puts "Pass"
else
puts "expected [2, 4, 42, 83, 34], got #{result1.inspect}"
end
if (result2 = array2.find_duplicates(array1)) == [83, 34, 2, 42, 4]
puts "Pass"
else
puts "expected [83, 34, 2, 42, 4], got #{result2.inspect}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment