fork download
  1. const powerset = (array) => {
  2. const result = [[]];
  3.  
  4. const arrayPower = Math.pow(2, array.length);
  5. for (let index = 1; index < arrayPower; ++index){
  6. const subset = [];
  7. for (let i = 0; i < array.length; i++){
  8. const subsetPower = Math.pow(2, i);
  9. if (index & subsetPower){
  10. subset.push(array[i]);
  11. }
  12. }
  13.  
  14. result.push(subset);
  15. }
  16.  
  17. return result;
  18. };
  19.  
  20. for(const set of powerset([1,2,3])) console.log(`subset: ${set}`);
Success #stdin #stdout 0.02s 17020KB
stdin
Standard input is empty
stdout
subset: 
subset: 1
subset: 2
subset: 1,2
subset: 3
subset: 1,3
subset: 2,3
subset: 1,2,3