Skip to content

Instantly share code, notes, and snippets.

@rocktronica
Created June 11, 2012 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rocktronica/2908317 to your computer and use it in GitHub Desktop.
Save rocktronica/2908317 to your computer and use it in GitHub Desktop.
nextUp(); getting next higher permutation of number
// 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;
}());
}
@rocktronica
Copy link
Author

That iterator smells really inefficient, but it works. Hmmm.....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment