Skip to content

Instantly share code, notes, and snippets.

@john45
Last active March 17, 2020 22:01
Show Gist options
  • Save john45/5c58db717704763cae2e29c487798112 to your computer and use it in GitHub Desktop.
Save john45/5c58db717704763cae2e29c487798112 to your computer and use it in GitHub Desktop.
# You have an array of ints. Create function which groups numbers by sum of pairs
# (for example: sum = 5). Each element of array has to be used only once.
# function getPairs(arr, sum) {
# // ...
# }
# ---
# test data:
# input: [22, 3, 5, 0, 2, 2]
# resutls: [[3, 2], [5, 0]]
# input: [-5, 33, 2, 2, 3, 5, 0, 10, 3]
# resutls: [[-5, 10], [2, 3], [2, 3], [5, 0]]
# input: [5, 5, 5, 0, 0, 0, 5]
# resutls: [[5, 0], [5, 0], [5, 0]]
# sum=6
# input: [3, 3, 6, 0]
# resutls: [[3, 3], [6, 0]]
# # Language: JavaScript or Ruby (of your choice)
param = 5
input = [-5, 33, 2, 2, 3, 5, 0, 10, 3]
def get_pairs(arr, sum)
result = []
comb = arr.combination(2).to_a
comb.each do |pair|
if pair.sum == sum && arr.any?
if arr.find_index(pair[0]) && arr.find_index(pair[1])
arr.delete_at(arr.find_index(pair[0])) && arr.delete_at(arr.index(pair[1]))
result << pair
end
end
end
result
end
p get_pairs(input, param)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment