How to combine array of strings in all possible ways
Example 1
input
const words = ["foo", "bar"]
Output
["foobar", "barfoo"]
Example 2
input
const words = ["word","good","best"];
Output
[
"wordgoodbest",
"wordbestgood",
"bestwordgood",
"bestgoodword",
"goodbestword",
"goodwordbest"
]
And so on if input size increased
CodePudding user response:
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.
CodePudding user response:
I don't know how efficient it would be but might get you what you need.
- Remove duplicate entries from input array
- outer loop n times (total no of elements in input array)
- inner loop n-1 times (all elements except current outer loop)