I have the following problem. I have some words (let's say 3): word1 word2 word3, all of them separated by white spaces and I want to generate all the combinations (3! that mean 6) like word1 word2 word3... word2 word1 word3... word2 word3 word1... word3 word2 word1... word3 word1 word2... word1 word3 word2... Can you help me with a generic code that works for any number of words?
Asked
Active
Viewed 226 times
-2
-
I think you can use some recursive methods.... share what you had tried so far.. – Pranav C Balan Jan 05 '17 at 08:05
-
nothing that is the problem I don't know from where to start – S. Georgian Jan 05 '17 at 08:08
-
1http://stackoverflow.com/questions/39927452/recursively-print-all-permutations-of-a-string-javascript – Pranav C Balan Jan 05 '17 at 08:11
-
2http://stackoverflow.com/questions/9960908/permutations-in-javascript – Pranav C Balan Jan 05 '17 at 08:11
1 Answers
0
You can use one of the solutions provided to "Permutations in JavaScript?". You just need to split your string into words, and join the words back into a string for each permutation.
ES6 demo:
function* permute(permutation) {
var length = permutation.length,
c = Array(length).fill(0),
i = 1;
yield permutation;
while (i < length) {
if (c[i] < i) {
var k = i % 2 && c[i];
[permutation[i], permutation[k]] = [permutation[k], permutation[i]];
++c[i];
i = 1;
yield permutation;
} else {
c[i++] = 0;
}
}
}
// sample input:
var s = 'this is a test';
for (var words of permute(s.split(/\s+/))) {
console.log(words.join(' '));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }