Skip to content

Instantly share code, notes, and snippets.

@sunloverz
Created February 10, 2021 13:51
Show Gist options
  • Save sunloverz/234608ea4594e17171f456675b3c5a29 to your computer and use it in GitHub Desktop.
Save sunloverz/234608ea4594e17171f456675b3c5a29 to your computer and use it in GitHub Desktop.
Sum of pairs in ruby
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