Generating Permutations in Javascript

I’ve recently been working on a number puzzle which involved generating permutations. It involves finding permutations of a ten digit number. I decided to code this in Javascript. I found the following on Wikipedia:

The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place. 

Find the highest index i such that s[i] < s[i+1]. If no such index exists, the permutation is the last permutation.
Find the highest index j > i such that s[j] > s[i]. Such a j must exist, since i+1 is such an index.
Swap s[i] with s[j].
Reverse all the order of all of the elements after index i
.

This is my implementation of the above algorithm, adapted to generate all permutations after a given permutation, and allowing for user input and giving feedback:

document.getElementById("clickMe").addEventListener("click", getPermutations, false);

function getPermutations() {
message = document.getElementById("message");
s = document.getElementById("startPerm").value;
x = 1;
message.innerHTML = "<p>" + x + " " + s + "";
t = getNextPerm(s);
while (t != "") {
s = t;
x++;
message.innerHTML = message.innerHTML + "<p>" + x + " " + s + "</p>";
t = getNextPerm(s);
}
}

function getNextPerm(s) {
//create array of elements
n = s.length;
const elements = [];
for (z = 0; z < n; z++) elements[z] = s.substring(z, z + 1);
//find the largest index k such that elements[k] < elements[k + 1]
for (k = n - 2; k >= 0; k--) {
if (elements[k] < elements[k + 1]) {
//find the largest index l greater than k such that elements[k] < elements[l]
for (l = n - 1; l > k; l--) {
if (elements[k] < elements[l]) {
//swap elements k and l
sTemp = elements[k];
elements[k] = elements[l];
elements[l] = sTemp;
//reverse remainder of string
k++;
n--;
while (k < n) {
sTemp = elements[k];
elements[k] = elements[n];
elements[n] = sTemp;
k++;
n--;
}
//create string from array elements
t = "";
for (z = 0; z < elements.length; z++) t = t + elements[z];
return t;
}
}
}
}
//not found
return "";
}

You can test the code here (this will open the page in a new tab). Enter a piece of text and then click on the button. It will list permutations of the text.

I will be using this code in my next post to solve the puzzle.

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *