Created
January 24, 2016 16:00
-
-
Save trys/14ab97703c14cbf0e779 to your computer and use it in GitHub Desktop.
Problem 24
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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