我有一个函数,可以按数字总和对整数数组进行排序,如果数字总和等于数字值排序。这是函数:
function s(g){
var r=0;
while(g)r+=g%10,g/=10;
return r;
}
function digitalSumSort(a) {
a.sort(function(x,y){
return s(x)!=s(y)?s(x)-s(y):x-y;
});
return a;
}
有时工作正常,但在这个测试数据上失败了:
输入:[100, 22, 4, 11, 31, 103]
输出:[100, 11, 31, 4, 22, 103]
预期输出:[100, 11, 4, 22, 31, 103]
我不明白为什么会这样,以及如何解决它?
注意:代码中包含尽可能少的字符非常重要!
编辑:
这个问题已经得到解答,但我最近犯了同样的错误并想到了这一点。有没有办法制作var
充当 integer
(而不是 double
)当给定数值时。我学会了使用地板的技巧,但有时我只想 integer
操作而不是 double
(对于某些系统,它们更快,我可能还有其他原因)。
最佳答案
主要问题在于 s
函数,因为当 g 为分数时,它会继续循环并收集值。
此外,您可以使用Schwartzian transform,而不是在排序时计算值。又名装饰-排序-取消装饰。您使用计算值创建一个数组,您将使用该计算值对数组进行排序,然后映射回原始值。
function s(g) {
var r = 0;
while (g) r += g % 10, g = Math.floor(g/10); // round g down to skip redundent loops when g is a fraction
return r;
}
function digitalSumSort(a) {
return a
.map(function(n) { // create an array with theorigina and the computed values
return [s(n), n];
})
.sort(function(a, b) {
return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]; // sort by the computed or original values
})
.map(function(n) { // get back an array of the original values
return n[1];
});
}
console.log(digitalSumSort([100, 22, 4, 11, 31, 103])); // [100, 11, 4, 22, 31, 103]
关于即使使用比较函数,Javascript 按数字总和排序也不起作用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325722/