I came across a mock interview question in which the candidate is asked to generate the powerset of a given set.
The input set is represented as a unique array of integers.
There was no solution provided in this instance, so I tried to see what i could come up with on my own. I did struggle my way to a solution and I'm not particularly dissatisfied with it, but I'm not particularly satisfied either.
I took a recursive approach. Essentially, I generated a tree, depth first, with the uppermost level consisting of the original set and each successive lower level consisting of the immediate subsets of the parent node.
Here's my code. I am using ES5.
var result = generate_powerset([1, 2, 3, 4]);
console.log(result);
function generate_powerset(set) {
var powerset = generate_subsets(set);
powerset.push(set);
return powerset;
}
function generate_subsets(set) {
var subsets = [];
set.forEach(function(element, i) {
var immediate_subset = remove_index(set, i);
maybe_push(subsets, immediate_subset);
var extended_subsets = generate_subsets(immediate_subset);
extended_subsets.forEach(function(extended_subset) {
maybe_push(subsets, extended_subset);
});
});
return subsets;
}
function remove_index(array, i) {
return array.filter(function(el, j) {
return i != j;
});
}
function maybe_push(set, non_member) {
var already_member = false;
set.forEach(function(member) {
if (are_identical(member, non_member)) already_member = true;
})
if (!already_member) set.push(non_member);
}
function are_identical(set1, set2) {
return (JSON.stringify(set1.sort()) == JSON.stringify(set2.sort()));
}
I'm looking for ways to:
- Make this algorithm more efficient
- Make this code easier to understand
- Make my code shorter
I'm also just generally curious if this approach is considered orthodox or unorthodox.