skip to Main Content

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


  1. You could take a recursive approach and get arrays with undefined plus rest and the value plus rest.

    const
        getAllSubsets = ([value, ...rest]) => {
           const sub = rest.length ? getAllSubsets(rest) : [[]];
           return [
               ...sub.flatMap(a => [[undefined, ...a]]),
               ...sub.flatMap(a => [[array[0], ...a]]),
           ];
        };
    
    console.log(getAllSubsets([1, 2, 3]));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
  2. 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search