Skip to content

Instantly share code, notes, and snippets.

@fredwu
Created September 27, 2010 03:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fredwu/598577 to your computer and use it in GitHub Desktop.
Save fredwu/598577 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], [-1, 0, 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)
@samqiu
Copy link

samqiu commented Sep 27, 2010

围观 from kohana group..

@skandhas
Copy link

skandhas commented Mar 2, 2012

p Sumify::run(5, (-1..4).to_a)为例,原来的算法会漏下[-1,0,1,2,3]这一组,不知我的理解对不对?
按我对题意的理解,在你的基础上修改了一下:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment