# subset

unknown

javascript

2 years ago

1.2 kB

11

Indexable

Never

^{}

function subsets(array){ // base case if(array.length === 0) return [[]]; //get the current element, taking hostage of this for now let current_element = array[0]; //1 //now, strategy is to recurse until we get an empty array and return [[]]. //with [[]] we will then go backup and add current_element that we took hostage to it at each step. //the reason why we need the base case is because that is our initial array we are going to update the subsets into and return (base case is the array we update/add to) let subset_items = subsets(array.slice(1)) //[[]] //now we have current_element, and the subsets we need to make a copy of and add to. let new_subset = []; for(let i=0; i<subset_items.length; i++){ //make copy of each one in subset_items (call that is returned) let sub_copy = subset_items[i].slice() //i.e. [] // push element into the subset copy sub_copy.push(current_element); //[1] //push the new copy to new_subset new_subset.push(sub_copy); } //combine the previous subset_items with the new copy that we added the hostage to. [[]] + [[1]] = [[], [1]] let final_result = subset_items.concat(new_subset); return final_result; }