Here I have written a program that will find all the subsets array, like if the array is [1, 2, 3]
, and I want output like [[], 2],, 2, , [2, 1], 3, , [3, 1], [3, 2], [3
I have written a program that represents the binary logic representation. The output is not coming as expected.
Can you please rectify and modify that programme?
const getAllSubsets = arr => {
let n = arr.length
let add = []
for (let i = 0; i < (1 << n); i++) {
for (let j = 0; j < n; j++) {
if ((1 << j) & i) {
add.push([arr[j]])
}
}
}
return add
}
console.log(getAllSubsets([1,2,3]))
2
Answers
You could take a recursive approach and get arrays with undefined plus rest and the value plus rest.
You need two storage arrays: one for all subsets, and one for the current one. The overall schema of your code would be like this:
Good luck!