Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created March 11, 2013 00:46
Show Gist options
  • Select an option

  • Save hiroshi-maybe/5131224 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/5131224 to your computer and use it in GitHub Desktop.
Provide power set with recursive function calls.
var power_set = function (set) {
var array=[[]],
sub_set = function(n,m) {
// should return 2 dimensions array
var result = [];
if (m==1) {
result.push([set[n]]);
} else {
for(var i=n, length=set.length; i<length-1; i+=1) {
var subset = sub_set(i+1, m-1);
for (var j=0; j<subset.length; j+=1) {
var new_set = subset[j];
new_set.push(set[n]);
result.push(new_set);
}
}
}
return result;
};
for(var i=0, length=set.length; i<length; i+=1) {
for (var j=1; j<length+1; j+=1) {
var temp = sub_set(i, j);
for (var k=0; k<temp.length; k+=1) {
array.push(temp[k]);
}
}
}
return array;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment