Skip to content

Instantly share code, notes, and snippets.

@kareemgrant
Created May 23, 2015 17:50
Show Gist options
  • Save kareemgrant/fe244787d27fb1463f62 to your computer and use it in GitHub Desktop.
Save kareemgrant/fe244787d27fb1463f62 to your computer and use it in GitHub Desktop.
# Given an array of n numbers with exactly one duplicate, write a program that finds the duplicate number in an efficient manner
require 'minitest/autorun'
def find_duplicate(numbers_array)
# using an hash as a way to keep track of evaluted numbers
checked_numbers = {}
numbers_array.each do |number|
return number if checked_numbers[number] != nil
checked_numbers[number] = number
end
'no duplicate found'
end
class FindDuplicatesTest < MiniTest::Unit::TestCase
def test_returns_message_with_no_duplicates
assert_equal 'no duplicate found', find_duplicate([1, 2, 3].shuffle)
end
def test_returns_duplicate_with_small_array
assert_equal 3, find_duplicate([1, 2, 3, 3].shuffle)
end
def test_returns_duplicate_with_larger_array
assert_equal 9999, find_duplicate((1..9999).to_a.shuffle << 9999)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment