Last active
August 6, 2019 19:46
-
-
Save brandonbarringer/87f7af3100d330743dc4 to your computer and use it in GitHub Desktop.
subset sum
This file contains hidden or 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
/* | |
You are given an array of integers ARR and an integer SUM. | |
Your task is to find the number of subsets of the array ARR, such that the sum of their elements equals SUM | |
Example: | |
SubsetSum([1,2,3,4,5], 5) = 3 | |
These subsets are [1,4], [2,3] and [5]. | |
SubsetSum([1,2,3,4,-5], 0) = 3 | |
These subsets are [1,4,-5], [2,3,-5] and []. | |
*/ | |
SubsetSum = (x, u) => { | |
p = [] | |
for (m = 1; m < 1 << x.length; m++) p[m] = ( x.filter((v, i) => ((m >> i) & 1) == 1) ) | |
r = p.filter( b => b.reduce((a,b) => a+b) == u).length | |
return u == 0 ? r+1 : r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment