Search code examples
javascriptarraysdata-structures

find all subset of arrays in js


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]))


Solution

  • 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:

    const getAllSubsets = arr => {
        let subsets = []
        
        OUTER LOOP {
            let subset = []
            INNER LOOP {
                if ...
                    subset.push(arr[j])
            }
            subsets.push(subset)
        }
    
        return subsets
    }
    

    Good luck!