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

One thought on “To print all the possible combinations of the words in a string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s