I have an array of type String in Javascript. Eg: ["ab", "cd", "ef", "gh"] This array is not fixed & is alphabetically ordered.
I want an output like this:
ab
abcd
abef
abgh
abcdef
abcdgh
abefgh
abcdefgh
cd
cdef
cdgh
cdefgh
ef
efgh
I have an array of type String in Javascript. Eg: ["ab", "cd", "ef", "gh"] This array is not fixed & is alphabetically ordered.
I want an output like this:
ab
abcd
abef
abgh
abcdef
abcdgh
abefgh
abcdefgh
cd
cdef
cdgh
cdefgh
ef
efgh
Use this for creating the power set of x:
function power(x) {
var r = [""], // start with empty set/string
l = 1;
for (var i=0; i<x.length; l=1<<++i) // OK, l is just r[i].length, but this looks nicer :)
for (var j=0; j<l; j++) {
r.push(r[j].slice(0)); // copy
r[j] += x[i];
}
return r;
}
Usage:
> power(["ab", "cd", "ef", "gh"])
["abcdefgh", "cdefgh", "abefgh", "efgh", "abcdgh", "cdgh", "abgh", "gh", "abcdef", "cdef", "abef", "ef", "abcd", "cd", "ab", ""]
I agree with robin that you should try yourself first, but here it is (with help from lodash library):
function combos(arr) {
if(arr.length <= 1) return arr
return _.flatten(arr.map(function(key, index) {
return [[key]].concat(
combos(arr.slice(index+1))
.map(function(combo) { return [key].concat(combo) })
)
}))
}
console.log(
combos(["a", "b", "c", "d"])
.map(function(arr) { return arr.join("")})
)