Skip to content

Instantly share code, notes, and snippets.

@trys
Created January 24, 2016 16:00
Show Gist options
  • Save trys/14ab97703c14cbf0e779 to your computer and use it in GitHub Desktop.
Save trys/14ab97703c14cbf0e779 to your computer and use it in GitHub Desktop.
Problem 24
var permutations = [],
numberArray = '1234567890'.split('');
function swap(a, b) {
var tmp = numberArray[a];
numberArray[a] = numberArray[b];
numberArray[b] = tmp;
}
// Use Heap's algorithm to swap around numbers
// @see https://en.wikipedia.org/wiki/Heap's_algorithm
function getPermutations(n) {
if (n == 1) {
permutations.push(numberArray.join(''));
} else {
for (var i = 0; i != n; ++i) {
getPermutations(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}
}
getPermutations(numberArray.length);
permutations.sort();
document.body.innerHTML = permutations[1000000-1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment