Skip to content

Commit d671327

Browse files
authored
feat: added find subsets algorithm using bitmanipulation (TheAlgorithms#1514)
* feat: added find subsets algorithm using bitmanipulation * file name fix * test file name fix * fix: codespell fix * error handled * added test cases for error
1 parent f67cdc3 commit d671327

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

Bit-Manipulation/GenerateSubSets.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @function generateSubSets
3+
* @param {Array} inputArray
4+
* @returns {Array}
5+
* @example [1,2] -> [[],[1],[2],[1,2]]
6+
*/
7+
8+
// The time complexity of this algorithm is BigO(2^n) where n is the length of array
9+
function generateSubSets(inputArray) {
10+
if (!Array.isArray(inputArray)) {
11+
throw new Error('Provided input is not an array')
12+
}
13+
if (inputArray.length > 32) {
14+
throw new RangeError('Error size should be less than equal to 32')
15+
}
16+
let arrayLength = inputArray.length
17+
let subSets = []
18+
// loop till (2^n) - 1
19+
for (let i = 0; i < 1 << arrayLength; i++) {
20+
let subSet = []
21+
for (let j = 0; j < arrayLength; j++) {
22+
// 1 << j it shifts binary digit 1 by j positions and then we perform
23+
// and by AND operation we are checking whetheer jth bit
24+
// in i is set to 1 if result is non zero just add into set
25+
if (i & (1 << j)) {
26+
subSet.push(inputArray[j])
27+
}
28+
}
29+
subSets.push(subSet)
30+
}
31+
return subSets
32+
}
33+
34+
export { generateSubSets }
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { generateSubSets } from '../GenerateSubSets'
2+
3+
describe('subSets', () => {
4+
it('find the subsets', () => {
5+
expect(generateSubSets([1, 2, 3])).toEqual([
6+
[],
7+
[1],
8+
[2],
9+
[1, 2],
10+
[3],
11+
[1, 3],
12+
[2, 3],
13+
[1, 2, 3]
14+
])
15+
expect(generateSubSets([1, 2])).toEqual([[], [1], [2], [1, 2]])
16+
expect(generateSubSets([1, 2, 3])).toEqual([
17+
[],
18+
[1],
19+
[2],
20+
[1, 2],
21+
[3],
22+
[1, 3],
23+
[2, 3],
24+
[1, 2, 3]
25+
])
26+
expect(() => generateSubSets('invalid')).toThrow(
27+
'Provided input is not an array'
28+
)
29+
expect(() =>
30+
generateSubSets([
31+
1, 2, 2, 1, 2, 3, 4, 3, 2, 3, 4, 3, 2, 2, 2, 3, 12, 11, 4, 2, 2, 2, 2,
32+
1, 2, 3, 5, 6, 7, 7, 8, 6, 5, 6, 7, 8, 9, 8, 0, 6
33+
])
34+
).toThrow('Error size should be less than equal to 32')
35+
})
36+
})

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