Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

All possible ways to combine array of strings uniquely

How to combine array of strings in all possible ways

Example 1

input

const words = ["foo", "bar"]

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["foobar", "barfoo"]

Example 2

input

const words = ["word","good","best"];

Output

[
  "wordgoodbest",
  "wordbestgood",
  "bestwordgood",
  "bestgoodword",
  "goodbestword",
  "goodwordbest"
]

And so on if input size increased

>Solution :

function combineWords(words) {
  const result = [];

  if (words.length === 1) {
    return words;
  }

  for (let i = 0; i < words.length; ++i) {
    const word = words[i];

    const rest = words.slice(0, i).concat(words.slice(i + 1));

    const combinations = combineWords(rest);

    for (let j = 0; j < combinations.length; ++j) {
      result.push(word + combinations[j]);
    }
  }

  return result;
}

// Example by OP in original question
console.log(combineWords(["word","good","best"]))
// Example by OP in comments
console.log(combineWords(["word", "good", "best", "hi"]))
// permutations are length of input factorial
console.log(combineWords(["word","good","best", "another", "more"]).length)

The function first checks if the array only contains one word. If so, it simply returns the array.

Otherwise, it loops through all the words in the array. For each word, it creates a new array that contains all the other words in the original array, excluding the current word. It then calls the function recursively on this new array, which will return an array of all possible combinations of the words in this new array.

Finally, it loops through all the combinations returned by the recursive call and appends the current word to each one, before adding it to the final array of results.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading