Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hlee/1969785 to your computer and use it in GitHub Desktop.
Save hlee/1969785 to your computer and use it in GitHub Desktop.

Given an integer, and a range of integers (both positive and negative) as input.

We need to calculate the possible combinations of the integers from the range that add up to the given integer.

For example:

Integer: 5

Range: -1, 0, 1, 2, 3, 4

Result: [1, 4], [2, 3], [-1, 2, 4], [0, 1, 4], [0, 2, 3], [-1, 0, 2, 4], [-1, 1, 2, 3]

# ruby example
class Sumify
def self.run(num, collection)
collection.size.times.map { |n| collection.combination(n).to_a }.flatten(1).select { |c| c.inject(:+) == num }
end
end
# p Sumify::run(5, (-1..4).to_a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment