-1

I need to be able to take a list of strings, and come up with a list of all possible combinations of those strings combined.

["asdf", "ghj","ew","ptum"]

It should get a list something like this, up to n

["agep", "aget", "ageu", ... "fjwm"]

What would I do to get these?

Corbbin Goldsmith
  • 387
  • 1
  • 3
  • 9

2 Answers2

0

You can create an array of letters from the list of strings , like in your case -> list of strings :

list = ["asdf", "ghj","ew","ptum"]

array of letters would be :-

arr = ["a","s",...,"m"]

then iterate through the array, for each letter make combination with other letters in array ...

the logic will be like this...

//for strings of length 3 ..
for(i in arr){
   for(j in arr){
      for(k in arr){
          if(i!=j && j!=k)
              result=i+j+k
                   }
                }
             }

p.s I am not into JS , I just told one logic to do this , you can now implent the logic in your language.

Partha Roy
  • 1,575
  • 15
  • 16
0

What you are asking is relatively trivial... some for loops can do this fairly easily. Below is one such method you could use.

var input = ["asdf", "ghj", "ew", "ptum"];

function combinations(r, n) {
  var o = [];
  if (r.constructor.name === "String")
    r = r.split("");
  if (n.constructor.name === "String")
    n = n.split("");

  r.forEach(function(i) {
    n.forEach(function(j) {
      o.push(i + j);
    })
  })
  return o;
}

document.write("<pre>"+JSON.stringify(input.reduce(combinations),null,2)+"</pre>");
Goblinlord
  • 3,290
  • 1
  • 20
  • 24
  • WOAH!!!! Thank you! I never even knew about reduce... :( I learn something new every day. This will come in handy later. Thanks again. – Corbbin Goldsmith Jan 29 '16 at 19:35
  • While this is good, it doesn't work for less than 2 strings. Like if I have string `"io"` it should get both i & o, but it doesn't. I'm just going to pass each of the characters when the length of the strings is 1 and not do the reduce. – Corbbin Goldsmith Jan 30 '16 at 08:43
  • not sure why you would want to use it with a single string as you can just do "io".split("") and you have your list. You could easily filter for that but in the context you gave it didn't make much sense to make it that way – Goblinlord Jan 30 '16 at 10:14