Guest User

Untitled

a guest
Jun 23rd, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. const powerSet = (array) => {
  2. const results = [];
  3.  
  4. const maximum = 1 << array.length;
  5. let reference = 0;
  6.  
  7. while (reference < maximum) {
  8. results.push(array.filter((element, index) => reference & 1 << index));
  9. reference++;
  10. }
  11.  
  12. return results;
  13. };
  14.  
  15.  
  16. const powerSetRecursive = ([first, ...rest]) => {
  17. if (rest.length === 0) {
  18. return [[], [first]];
  19. }
  20. const results = powerSetRecursive(rest);
  21. return results.concat(results.map(element => [first, ...element]));
  22. };
  23.  
  24.  
  25. const test = array => {
  26. const result = powerSet(array);
  27. const recursive = powerSetRecursive(array);
  28. console.log(result);
  29. console.log(recursive);
  30. console.log(result.length === 2 ** array.length);
  31. console.log(result.length === recursive.length);
  32. };
  33.  
  34. test([1, 2, 3, 4, 5, 10])
Add Comment
Please, Sign In to add comment