Skip to content

Commit d4a67d5

Browse files
authored
Merge pull request ashutosh97#76 from miketu926/powerset
Added Powerset
2 parents 59e2fbd + 761cc52 commit d4a67d5

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Powerset/powerset.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// given an array, provide all subsets (powersets);
2+
3+
// [1,3,2]
4+
// => [[],[1],[2],[3],[1,3],[1,2][2,3],[1,2,3]]
5+
6+
const powerSet = (arr) => {
7+
const result = [];
8+
9+
const _recurse = (chosen, remaining) => {
10+
if (remaining.length === 0) {
11+
result.push(chosen);
12+
} else {
13+
_recurse(chosen, remaining.slice(1));
14+
_recurse(chosen.concat(remaining[0]), remaining.slice(1));
15+
}
16+
};
17+
18+
_recurse([], arr);
19+
return result;
20+
}
21+
22+
console.log(powerSet([1, 2, 3]));

Powerset/question.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
given an array, provide all subsets (powersets);
2+
3+
result:
4+
[1,3,2]
5+
[[],[1],[2],[3],[1,3],[1,2][2,3],[1,2,3]]

0 commit comments

Comments
 (0)