Last active
August 29, 2015 14:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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