Created
June 11, 2012 03:04
-
-
Save rocktronica/2908317 to your computer and use it in GitHub Desktop.
nextUp(); getting next higher permutation of number
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
// Given a number, find the next higher number which has the exact same set of digits as the original number | |
// http://stackoverflow.com/questions/9368205/given-a-number-find-the-next-higher-number-which-has-the-exact-same-set-of-digi | |
function nextUp(iNumber){ | |
var sDigitsSorted = iNumber.toString().split('').sort().join(''); | |
var aPermutations = (function(){ | |
var i = parseInt(iNumber.toString().split('').sort().reverse().join(''),10) + 1, | |
a = []; | |
// this is crazy inefficient | |
while (i--) { | |
var sSorted = i.toString().split('').sort().join(''); | |
if (sSorted.length !== sDigitsSorted.length) { break; } | |
if (sSorted === sDigitsSorted) { a.push(i); } | |
} | |
return a.sort(); | |
}()); | |
return (function(){ | |
var iCount = aPermutations.length; | |
for (var i=0; i<iCount; i++){ | |
var iPermutation = aPermutations[i]; | |
if (iPermutation > iNumber) { | |
return iPermutation; | |
} | |
} | |
return null; | |
}()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That iterator smells really inefficient, but it works. Hmmm.....