Have the function nextLargest(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).
Examples
Input: 11121 Output: 11211 Input: 41352 Output: 41523
var permute = (function () {
return permute;
function permute(list) {
return list.length ?
list.reduce(permutate, []) :
[[]];
}
function permutate(permutations, item, index, list) {
return permutations.concat(permute(
list.slice(0, index).concat(
list.slice(index + 1)))
.map(concat ,[item]));
}
function concat(list) {
return this.concat(list);
}
}());
console.log(JSON.stringify(permute([1,2,3,4])));
my output : [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]]
expected output :
Input: 11121
Output: 11211
Input: 41352
Output: 41523
Assuming the permute function as given that you shared in your question, the following straightforward approach should solve the question.
It is not very efficient, however. Probably, a better strategy could be found working with a cleverly chosen sequence of transpositions only.
function nextLargest(input) {
let x = input.toString();
let p = permute([...x]);
let result = Infinity;
for (let n of p) {
let y = n.join('')*1;
if (y > input && y < result) result = y;
}
return result < Infinity ? result : -1;
}
console.log(nextLargest(1234)); // <<< gives 1243