Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Last active January 1, 2016 06:39
Show Gist options
  • Save elreimundo/8106594 to your computer and use it in GitHub Desktop.
Save elreimundo/8106594 to your computer and use it in GitHub Desktop.
A program to determine all pairs of integers in a given array of integers that add to 100. The algorithm is destructive on the original array. This particular algorithm runs in N lg N time and constant space if the sorting algorithm is efficient; after the sort, only one additional pass through the array is required.
def hundred_pairs(array, target = 100)
array.sort!
results = []
min, max = array.shift, array.pop
while min && max
while min + max > target
max = array.pop
end
while min && max && min + max < target
min = array.shift
end
if min && max && min + max == target
results << [min,max]
min, max = array.shift, array.pop
end
end
results
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment