subsets

 avatar
user_1671475754
javascript
2 years ago
1.1 kB
1
Indexable
Never
// iterative
let subsetsI = array =>{
  let subsets = [[]];

  for(let i=0; i<array.length; i++){
    let ele_to_add = array[i];
    let subsets_length = subsets.length;

    for(let j=0; j<subsets_length; j++){
      let subset = subsets[j];
      let copy_of_subset = subset.slice() //[]
      copy_of_subset.push(ele_to_add);
      subsets.push(copy_of_subset)
    }
  }
  return subsets;
}


// recursive
const subsets = (arr) => { //[1]
  // this method adds each num from arr to each existing subset as a new copy (adds the first element i.e. 1 to [] --> [[], [1]])
  if (!arr.length) return [[]]; //we start at the base case, where the array is empty

  const subs = subsets(arr.slice(1)); //take subset of everything but the first element// [[]]

  const last = arr[0]; // getting first element (to be added after finding subsets)// 1

  //subs before below === [[]]
  return subs.concat(subs.map((el) => { //el = []
    let newArr = el.slice(0) //newArr = []
    newArr.push(last); //newArr = [1]
    return newArr;
  })); // now subs === [[], [1]]
}