Skip to content

Instantly share code, notes, and snippets.

@ang3lkar
Created February 28, 2017 15:03
Show Gist options
  • Save ang3lkar/cf1fa2959a7dc75e9e25ed4829940bff to your computer and use it in GitHub Desktop.
Save ang3lkar/cf1fa2959a7dc75e9e25ed4829940bff to your computer and use it in GitHub Desktop.
Pair with sum problem
# 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)
@ang3lkar
Copy link
Author

Calculating -------------------------------------
        Brute Force:    19.948k i/100ms
        Combination:     3.576k i/100ms
        Functional:     65.712k i/100ms
        Set:            12.560k i/100ms
-------------------------------------------------
        Brute Force:    321.027k (±13.1%) i/s -      1.576M
        Combination:    195.988k (±15.8%) i/s -    954.792k
        Functional:       1.764M (±10.6%) i/s -      8.740M
        Set:            149.611k (±12.9%) i/s -    741.040k

Comparison:
        Functional: :  1763867.2 i/s
        Brute Force::   321027.5 i/s - 5.49x slower
        Combination::   195987.8 i/s - 9.00x slower
        Set:        :   149610.6 i/s - 11.79x slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment