Skip to content

Instantly share code, notes, and snippets.

@cschep
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cschep/d170c165286d6cc722a4 to your computer and use it in GitHub Desktop.
Save cschep/d170c165286d6cc722a4 to your computer and use it in GitHub Desktop.
/*
* 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);
@cschep
Copy link
Author

cschep commented Apr 16, 2015

[ 'j',
'ju',
'jmu',
'jmpu',
'jpu',
'jm',
'jmp',
'jp',
'u',
'mu',
'mpu',
'pu',
'm',
'mp',
'p' ]

correct answer?

@cschep
Copy link
Author

cschep commented Apr 16, 2015

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