Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Created April 26, 2013 15:57
Show Gist options
  • Select an option

  • Save ForbesLindesay/5468346 to your computer and use it in GitHub Desktop.

Select an option

Save ForbesLindesay/5468346 to your computer and use it in GitHub Desktop.
Generate permutations of an array in lexicographic order (using http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order)
function next(start) {
start = start;
//Find the largest index k such that a[k] < a[k + 1].
var k = start.length - 2;
while (k >= 0 && start[k] >= start[k + 1]) k--;
//If no such index exists, the permutation is the last permutation.
if (k < 0) return null;
//Find the largest index j such that a[k] < a[j].
//Since k + 1 is such an index, j is well defined and satisfies k < j.
var j = start.length - 1;
while (j > k && start[k] >= start[j]) j--;
if (j <= k) throw new Error('k should never be greater than j');
//Swap a[k] with a[j].
var temp = start[k];
start[k] = start[j];
start[j] = temp;
//Reverse the sequence from a[k + 1] up to and including the final element.
var result = [];
for (var i = 0; i <= k; i++) {
result.push(start[i]);
}
for (var i = start.length - 1; i > k; i--) {
result.push(start[i]);
}
return result;
}
var str = '0123456789'.split('');
for (var i = 1; i < 1000000; i++) str = next(str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment