Hi guys I am working on the following CoderByte problem.
Using the JavaScript language, have the function PermutationStep(num) take the num parameter being passed and return the next number greater than num using the same digits. For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999).
Use the Parameter Testing feature in the box below to test your code with different arguments.
My code is
var PermutationStep = function(num){
var newNum = num.toString().split("");
for(var i = (newNum.length - 1); i >= 0; i--){
if(newNum[i] > newNum[i-1]){
newNum.splice(i-1,2,newNum[i],newNum[i-1]);
var firstHalf = newNum.slice(0,i);
var secondHalf = newNum.slice(i);
break;
}
else{
return -1;
}
}
var sorted = secondHalf.sort(function(a,b){return a - b});
return firstHalf.concat(sorted).join("");
};
My code consists of looping through an array of the number and switching the terms newNum[i-1] and newNum[i] when newNum[i] > newNum[i - 1] and then taking all numbers to the right of these two terms and sorting them. Logically this works, but my code is not behaving the way I would like it to. For example PermutationStep(112211) returns -1 when it should be returning 121112. Can anyone help me debug this?