Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 29, 2018 00:17
Show Gist options
  • Save pinkmomo027/7f2a0b2fadec6c658801dac32b659f7e to your computer and use it in GitHub Desktop.
Save pinkmomo027/7f2a0b2fadec6c658801dac32b659f7e to your computer and use it in GitHub Desktop.
subsets of array
let names = ["fifi", "vampire", "lena", "wheels"];
let finalResult = [];
function sublist(array) {
let chosen = [];
sublistHelper(array, chosen);
}
function sublistHelper(array, chosen) {
if (array.length == 0) {
// base case
finalResult.push(Object.assign([], chosen));
} else {
let currentElement = array.shift();
// if select this element and explore
chosen.push(currentElement);
sublistHelper(array, chosen);
// if not select this element and explore
chosen.pop();
sublistHelper(array, chosen);
array.unshift(currentElement);
}
}
sublist(names);
console.log(finalResult);
@pinkmomo027
Copy link
Author

pinkmomo027 commented Jun 29, 2018

[ [ 'fifi', 'vampire', 'lena', 'wheels' ],
  [ 'fifi', 'vampire', 'lena' ],
  [ 'fifi', 'vampire', 'wheels' ],
  [ 'fifi', 'vampire' ],
  [ 'fifi', 'lena', 'wheels' ],
  [ 'fifi', 'lena' ],
  [ 'fifi', 'wheels' ],
  [ 'fifi' ],
  [ 'vampire', 'lena', 'wheels' ],
  [ 'vampire', 'lena' ],
  [ 'vampire', 'wheels' ],
  [ 'vampire' ],
  [ 'lena', 'wheels' ],
  [ 'lena' ],
  [ 'wheels' ],
  [] ]
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment