Last active
August 29, 2015 14:19
-
-
Save cschep/d170c165286d6cc722a4 to your computer and use it in GitHub Desktop.
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
/* | |
* Return an array with the power set of a given string. | |
* Definition of power set: The set of all possible subsets including the empty set. | |
* | |
* Example: | |
* | |
* powerSet("abc") | |
* -> [ '' , 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc' ] | |
* | |
* Note: | |
* 1. All characters in a subset should be sorted. | |
* 2. Sets of the same characters are considered duplicates regardless of order and count only once, e.g. 'ab' and 'ba' are the same. | |
* | |
* Example 2 : | |
* | |
* powerSet("jump") | |
* -> ["", "j", "ju", "jm", "jp", "jmu", "jmp", "jpu", "jmpu", "u", "m", "p", "mu", "mp", "pu", "mpu"] | |
*/ | |
var powerSet = function(str){ | |
var result = {}; | |
var options = str.split(""); | |
var recurse = function(options, current) { | |
for (var i = 0; i < options.length; i++) { | |
if (current.indexOf(options[i]) === -1) { | |
var newString = current + options[i]; | |
recurse(options, newString); | |
} else { | |
var s = current.split("") | |
var sorted = s.sort(); | |
s = sorted.join(""); | |
result[s] = s; | |
} | |
} | |
} | |
recurse(options, ""); | |
return Object.keys(result); | |
} | |
var result = powerSet('jump'); | |
console.log(result); |
results for balloon
[ 'b',
'ab',
'abl',
'ablo',
'ablno',
'abln',
'abo',
'abno',
'abn',
'bl',
'blo',
'blno',
'bln',
'bo',
'bno',
'bn',
'a',
'al',
'alo',
'alno',
'aln',
'ao',
'ano',
'an',
'l',
'lo',
'lno',
'ln',
'o',
'no',
'n' ]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[ 'j',
'ju',
'jmu',
'jmpu',
'jpu',
'jm',
'jmp',
'jp',
'u',
'mu',
'mpu',
'pu',
'm',
'mp',
'p' ]
correct answer?