Math Challenge在使用javascript进行混洗后打印第二大数字



让函数nextLargest(num(接受正在传递的num参数,并使用相同的数字返回下一个大于num的数字。例如:如果num是123,则返回132,如果是12453,则返回12534。如果一个数字没有更大的排列,则返回-1(即999(。

示例

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])));

我的输出:[[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]]

预期输出:

Input: 11121
Output: 11211
Input: 41352
Output: 41523

假设permute函数是您在问题中共享的函数,那么以下简单的方法应该可以解决问题。

然而,它的效率不是很高。也许,可以找到一种更好的策略,只使用巧妙选择的转座序列。

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

最新更新