Created
February 10, 2021 13:51
-
-
Save sunloverz/234608ea4594e17171f456675b3c5a29 to your computer and use it in GitHub Desktop.
Sum of pairs in ruby
This file contains 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
def get_pairs(arr, sum) | |
len = arr.length | |
seen = Array.new(len, false) | |
result = [] | |
for i in 0..len-1 | |
for j in i+1..len-1 | |
if arr[i] + arr[j] == sum && !seen[j] && !seen[i] | |
seen[i], seen[j] = true, true | |
result << [arr[i], arr[j]] | |
end | |
end | |
end | |
result | |
end | |
puts get_pairs([5, 5, 5, 0, 0, 0, 5], 5) | |
puts get_pairs([3, 3, 6, 0], 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment