Skip to content

Instantly share code, notes, and snippets.

@thorntonrose
Last active April 20, 2018 13:06
Show Gist options
  • Save thorntonrose/6d6c5468514c7b41187e to your computer and use it in GitHub Desktop.
Save thorntonrose/6d6c5468514c7b41187e to your computer and use it in GitHub Desktop.
Find pairs of numbers in an array with a given sum
def findPairs1(nums, limit) {
print "$nums, $limit => "
def pairs = []
nums.eachWithIndex { n1, i1 ->
nums.eachWithIndex { n2, i2 ->
if (i1 != i2 && (n1 + n2) == limit) {
pairs << [ n1, n2 ].sort()
}
}
}
pairs.unique()
}
def findPairs2(nums, limit) {
print "$nums, $limit => "
def mem = [:]
nums.collect { n ->
def diff = limit - n
if (!mem[diff]) {
mem[n] = 1
[]
} else {
[ n, diff ]
}
}.findAll()
}
println findPairs1([ 1, 98, 99, 2, 5 ], 100)
println findPairs1([ 50, 50 ], 100)
println findPairs1([ 5, 3, 7, 9, 6, 1 ], 10)
println findPairs2([ 1, 98, 99, 2, 5 ], 100)
println findPairs2([ 50, 50 ], 100)
println findPairs2([ 5, 3, 7, 9, 6, 1 ], 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment