-2

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?

meen
  • 2,287
  • 3
  • 23
  • 42
S. Georgian
  • 143
  • 1
  • 2
  • 11

1 Answers1

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; }
Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286