Skip to content

Instantly share code, notes, and snippets.

@gemfarmer
Created September 29, 2013 22:10
Show Gist options
  • Save gemfarmer/6757062 to your computer and use it in GitHub Desktop.
Save gemfarmer/6757062 to your computer and use it in GitHub Desktop.
Input a number Output the next largest number using the same combination of numbers.
function PermutationStep(num) {
var numString = num.toString();
var numArray = numString.split("")
var numArrayStart = [];
var numArrayEnd = [];
for (var i = numArray.length-1; i>0; i--) {
if(Number(numArray[i])<Number(numArray[i+1])){
numArrayStart.push(numString.substring(0,i))
numArrayEnd.push(numString.substring(i,numString.length));
break;
}
}
if(numArrayEnd[0]===undefined){
alert("a larger number with the same number combination does not exist");
}
var endSplitArray = numArrayEnd[0].split("");
var breakNumber = Number(endSplitArray[0]);
var endSplitArraySort = endSplitArray.sort();
for (var i = 0; i < endSplitArray.length; i++) {
if(Number(endSplitArray[i])>breakNumber){
numArrayStart.push(endSplitArray[i]);
endSplitArray.splice(i,1);
break;
}
}
var endSplitArrayRev = endSplitArray.join("").toString();
numArrayStart.push(endSplitArrayRev);
var output = Number(numArrayStart.join(""));
return output;
}
console.log("6345634563456=", PermutationStep(6345634563456));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment