Created
February 28, 2017 15:03
-
-
Save ang3lkar/cf1fa2959a7dc75e9e25ed4829940bff to your computer and use it in GitHub Desktop.
Pair with sum problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find a pair of elements from an array whose sum equals a given number | |
# | |
# * The array contains only integers | |
# * The array can have duplicates | |
# * Return a boolean that indicates if the list has such a pair | |
# * We will start with an ordered (ascending order) list example | |
require 'benchmark/ips' | |
require 'set' | |
def naive_approach(numbers, sum) | |
numbers.combination(2).any? { |a, b| a + b == sum } | |
end | |
def has_pairs_with_sum_functional(numbers, sum) | |
return false if numbers.size <= 1 | |
return true if numbers[1..-1].include?(sum - numbers[0]) | |
has_pairs_with_sum_functional(numbers[1..-1], sum) | |
end | |
def has_pair_with_sum_brute_force(input, sum) | |
0.upto(input.length - 1) do |n| | |
0.upto(input.length - 1) do |i| | |
if input[i] + input[n] == sum and n != i | |
return true | |
end | |
end | |
end | |
return false | |
end | |
def has_pair_with_sum_in_unordered_list(input, sum) | |
complements = Set.new | |
0.upto(input.length - 1) do |i| | |
value = input[i] | |
complement = sum - value | |
# if we have stored the value complement then we have a winner pair | |
if complements.include?(value) | |
return true | |
else | |
complements.add(complement) | |
end | |
end | |
return false | |
end | |
def test(array, sum = 100) | |
Benchmark.ips do |x| | |
x.report('Brute Force:') { has_pair_with_sum_brute_force array, sum } | |
x.report('Combination:') { naive_approach array, sum } | |
x.report('Functional: ') { has_pairs_with_sum_functional array, sum } | |
x.report('Set: ') { has_pair_with_sum_in_unordered_list array, sum } | |
x.compare! | |
end | |
end | |
array = 1.upto(100_000_000).map { rand(100) } | |
test(array) |
Author
ang3lkar
commented
Feb 28, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment