To print all the possible combinations of the words in a string

#!/usr/bin/env node

function swap(w, i, j) {
var tmp = w[i];
w[i] = w[j];
w[j] = tmp;
}

function permute(w, i, n) {
var j;

if (i == n) {
console.log(w.join(' '));
} else {
for (j = i; j < n; ++j) {
swap(w, i, j);
permute(w, i + 1, n);
swap(w, i, j);
}
}
}

var s = "This is String",
w = s.split(' ');

permute(w, 0, w.length);
Advertisements