Skip to content

Commit 1554ba5

Browse files
authored
test: add tests for NumberOfSubsetEqualToGivenSum (TheAlgorithms#1661)
1 parent 3623e42 commit 1554ba5

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
11
/*
2-
Given an array of non-negative integers and a value sum,
2+
Given an array of positive integers and a value sum,
33
determine the total number of the subset with sum
44
equal to the given sum.
55
*/
66
/*
77
Given solution is O(n*sum) Time complexity and O(sum) Space complexity
88
*/
99
function NumberOfSubsetSum(array, sum) {
10+
if (sum < 0) {
11+
throw new Error('The sum must be non-negative.')
12+
}
13+
14+
if (!array.every((num) => num > 0)) {
15+
throw new Error('All of the inputs of the array must be positive.')
16+
}
1017
const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i
1118
for (let i = 1; i <= sum; i++) {
1219
dp[i] = 0
@@ -23,10 +30,4 @@ function NumberOfSubsetSum(array, sum) {
2330
return dp[sum]
2431
}
2532

26-
// example
27-
28-
// const array = [1, 1, 2, 2, 3, 1, 1]
29-
// const sum = 4
30-
// const result = NumberOfSubsetSum(array, sum)
31-
3233
export { NumberOfSubsetSum }
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { NumberOfSubsetSum } from '../NumberOfSubsetEqualToGivenSum'
2+
3+
describe('Testing NumberOfSubsetSum', () => {
4+
it.each([
5+
[[], 0, 1],
6+
[[], 1, 0],
7+
[[1], 2, 0],
8+
[[1, 2, 3, 4, 5], 0, 1],
9+
[[1, 1, 1, 1, 1], 5, 1],
10+
[[1, 1, 1, 1, 1], 4, 5],
11+
[[1, 2, 3, 3], 6, 3],
12+
[[10, 20, 30, 1], 31, 2],
13+
[[1, 1, 2, 2, 3, 1, 1], 4, 18]
14+
])('check with %j and %i', (arr, sum, expected) => {
15+
expect(NumberOfSubsetSum(arr, sum)).toBe(expected)
16+
})
17+
18+
it.each([
19+
[[1, 2], -1],
20+
[[0, 2], 2],
21+
[[1, -1], 0]
22+
])('throws for %j and %i', (arr, sum) => {
23+
expect(() => NumberOfSubsetSum(arr, sum)).toThrowError()
24+
})
25+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy