Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active August 6, 2019 19:46
Show Gist options
  • Save brandonbarringer/87f7af3100d330743dc4 to your computer and use it in GitHub Desktop.
Save brandonbarringer/87f7af3100d330743dc4 to your computer and use it in GitHub Desktop.
subset sum
/*
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