-
-
Save schan90/b6fd564caf8c0dbbe30824c3c10fdb29 to your computer and use it in GitHub Desktop.
Javascript implementation(s) of a Power Set function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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) | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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