Skip to content

Instantly share code, notes, and snippets.

@rtacconi
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtacconi/b8cae8ddb23380b234c1 to your computer and use it in GitHub Desktop.
Save rtacconi/b8cae8ddb23380b234c1 to your computer and use it in GitHub Desktop.
return the number of combinations, of any length, that add up to that target_sum
def combinations(array)
m = array.length
(1...2**m).map do | n |
(0...m).select { | i | n[i] == 1 }.map { | i | array[i] }
end
end
def calculate_combinations(comb_array, target_sum=15)
combinations(comb_array).map {|a| [a, a.inject(:+)]}.select {|v| v if v.last == target_sum}
end
calculate_combinations([5, 5, 15, 10], target_sum=15).count
=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment