Skip to content

Instantly share code, notes, and snippets.

@lokothodida
Last active August 10, 2017 01:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lokothodida/b528e03059051f57439a to your computer and use it in GitHub Desktop.
Save lokothodida/b528e03059051f57439a to your computer and use it in GitHub Desktop.
Javascript implementation(s) of a Power Set function
/* Calculates the power set, P(s) := { s' : s' is a subset of s }
* Assumes an implementation of a Set that has the following methods:
* add, equals, forEach, clone
*/
var powerSet = function(set) {
var prevSet = new Set(); // prevSet := {}
var currSet = new Set().add(new Set()); // currSet := { {} }
// Main loop will continually add elements to currSet until no
// new elements are added
while (!currSet.equals(prevSet)) {
prevSet = currSet.clone();
// for c <- currSet:
currSet.forEach(function(currSetElem) {
// for e <- s:
set.forEach(function(setElem) {
// currSet := currSet U { c U {e} }
currSet.add(currSetElem.clone().add(setElem));
});
});
}
return currSet;
};
/* Some complexity analysis:
* The while loop is O(n), as it loops to compute the singletons, the doubles, the triples, ..., the n-tuples
* The currSet loop is O(2^n), as the largest it will be is 2^n
* The set loop is O(n^2), as the set loop is O(n) and the currSetElem.clone() call is O(n), so O(n*n)
* Thus the total complexity is O(n * n^2 * 2^n) = O(n^3 * 2^n)
*/
/* Recursive implementation
*/
var powerSet = function(set) {
var loop = function(prev, curr) {
if (!prev.equals(curr)) {
// Need to compute more elements of the power set
prev = curr.clone();
// for c <- currSet:
curr.forEach(function(currSetElem) {
// for e <- s:
set.forEach(function(setElem) {
// currSet := currSet U { c U {e} }
curr.add(currSetElem.clone().add(setElem));
});
});
return loop(prev, curr);
} else {
// All elements computed!
return curr;
}
};
// prev := {}, curr := { {} }
return loop(new Set(), new Set().add(new Set()));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment