Created
April 11, 2018 23:58
-
-
Save michaelhelvey/2ff95f0b6eacd1e780f93ec1cb48755b to your computer and use it in GitHub Desktop.
Demonstrates an algorithm for calculating power sets
This file contains 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
function pretty_print(set) { | |
set.forEach(item => { | |
console.log(JSON.stringify(item)); | |
}) | |
} | |
// where set is something of the form [item, item, item] | |
function get_power_set(set) { | |
// our result will itself be a set | |
let result = []; | |
const set_length = set.length; | |
// now for our algorithm. | |
let add_length = set_length; | |
let iterate_length = 1; | |
while (add_length > 0) { | |
// we now go through the array as many times as | |
// iterate_length, which will be 1 at the start, | |
// 2 next, etc, up to set_length-1; | |
for (let i = 0; i < iterate_length; i++) { | |
// add a subset of the original set to our result | |
result = [...result, set.slice(i, iterate_length)] | |
} | |
// decrement add_length and increment iterate_length | |
iterate_length++; | |
add_length -= 1; | |
} | |
// finally push the empty set | |
result = [...result, []]; | |
// order by size for readability | |
result.sort((a, b) => a.length > b.length); | |
return result; | |
} | |
// simple power set | |
const power_set = get_power_set(['a', 'b', 'c']); | |
// we can continue to get more abstract | |
const power_set_of_power_set = get_power_set(power_set); | |
// show some demonstrations | |
console.log('---POWER SET---' + `Cardinality: ${power_set.length}`); | |
pretty_print(power_set); | |
console.log('---NEXT ORDER POWER SET---' + `Cardinality: ${power_set_of_power_set.length}`); | |
pretty_print(power_set_of_power_set); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try it out here: https://codepen.io/helvetici/full/RMOady/