Created
December 21, 2015 22:50
-
-
Save mLuby/fe88d09ebf2ed599aa8c to your computer and use it in GitHub Desktop.
Generate power set from a string
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 powerset (input) { | |
return input | |
.split(input ? '' : false) | |
.filter(duplicates({})) | |
.map(concatEmptyStr) | |
.reduce(multiplyMatrix) | |
} | |
function concatEmptyStr (str) { | |
return str ? ['', str] : [''] | |
} | |
function multiplyMatrix (results, array) { | |
return results.reduce(function (aggr, item) { | |
return aggr.concat(array[0]+item, array[1]+item) // .push .push would be O(1) | |
}, []) | |
} | |
function duplicates (dupTracker) { | |
return function (item) { | |
return dupTracker[item] ? false : dupTracker[item] = true | |
} | |
} | |
console.log(powerset('').length === 1, powerset('')) | |
console.log(powerset('a').length === 2, powerset('a')) | |
console.log(powerset('ab').length === 4, powerset('ab')) | |
console.log(powerset('abc').length === 8, powerset('abc')) | |
console.log(powerset('abca').length === 8, powerset('abca')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment