0

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
1
  • 4
    Please show us your effort first. Do you have some code where you tried to address your problem? Commented Feb 18, 2015 at 11:19

2 Answers 2

2

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", ""]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Bergi. Power set did not come to my mind :P
0

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("")})
 )

http://jsbin.com/caxowuwuki/3/edit

1 Comment

Thanks Ollim..yes i will post from next time the code i tried to achieve this. It was good to learn about lodash library. New learning for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.