Skip to content

Instantly share code, notes, and snippets.

@adnils
Forked from rocktronica/nextup.js
Created January 30, 2014 15:03
Show Gist options
  • Save adnils/8710344 to your computer and use it in GitHub Desktop.
Save adnils/8710344 to your computer and use it in GitHub Desktop.
// 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