Skip to content

test: add tests for NumberOfSubsetEqualToGivenSum #1661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
/*
Given an array of non-negative integers and a value sum,
Given an array of positive integers and a value sum,
determine the total number of the subset with sum
equal to the given sum.
*/
/*
Given solution is O(n*sum) Time complexity and O(sum) Space complexity
*/
function NumberOfSubsetSum(array, sum) {
if (sum < 0) {
throw new Error('The sum must be non-negative.')
}

if (!array.every((num) => num > 0)) {
throw new Error('All of the inputs of the array must be positive.')
}
const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i
for (let i = 1; i <= sum; i++) {
dp[i] = 0
Expand All @@ -23,10 +30,4 @@ function NumberOfSubsetSum(array, sum) {
return dp[sum]
}

// example

// const array = [1, 1, 2, 2, 3, 1, 1]
// const sum = 4
// const result = NumberOfSubsetSum(array, sum)

export { NumberOfSubsetSum }
25 changes: 25 additions & 0 deletions Dynamic-Programming/tests/NumberOfSubsetEqualToGivenSum.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { NumberOfSubsetSum } from '../NumberOfSubsetEqualToGivenSum'

describe('Testing NumberOfSubsetSum', () => {
it.each([
[[], 0, 1],
[[], 1, 0],
[[1], 2, 0],
[[1, 2, 3, 4, 5], 0, 1],
[[1, 1, 1, 1, 1], 5, 1],
[[1, 1, 1, 1, 1], 4, 5],
[[1, 2, 3, 3], 6, 3],
[[10, 20, 30, 1], 31, 2],
[[1, 1, 2, 2, 3, 1, 1], 4, 18]
])('check with %j and %i', (arr, sum, expected) => {
expect(NumberOfSubsetSum(arr, sum)).toBe(expected)
})

it.each([
[[1, 2], -1],
[[0, 2], 2],
[[1, -1], 0]
])('throws for %j and %i', (arr, sum) => {
expect(() => NumberOfSubsetSum(arr, sum)).toThrowError()
})
})
Loading