JavaScript:添加最高达100%的四舍五入百分比



我正在从paxdiablo中寻找该算法的最短、最快的纯JavaScript实现,以添加高达100%的四舍五入百分比。

Value      CumulValue  CumulRounded  PrevBaseline  Need
---------  ----------  ------------  ------------  ----
0
13.626332   13.626332            14             0    14 ( 14 -  0)
47.989636   61.615968            62            14    48 ( 62 - 14)
9.596008   71.211976            71            62     9 ( 71 - 62)
28.788024  100.000000           100            71    29 (100 - 71)
---
100

const values = [13.626332, 47.989636, 9.596008 , 28.788024];
const round_to_100 = (arr) => {
let output = [];
let acc = 0;
for(let i = 0; i < arr.length; i++) {
let roundedCur = Math.round(arr[i]);
const currentAcc = acc;
if (acc == 0) {
output.push(roundedCur);
acc += arr[i];
continue;
}
acc += arr[i];
output.push(Math.round(acc) - Math.round(currentAcc));
}
return output;
}
console.log(round_to_100(values));

我的基准和唯一其他答案dshung的bar函数使用benchmark.js

mine x 17,835,852 ops/sec ±5.13% (80 runs sampled)
theirs x 1,785,401 ops/sec ±4.57% (84 runs sampled)
Fastest is mine

刚刚翻译了接受答案中的操作

const bar = (numbers) => {
const expectedSum = 100;
const sum = numbers.reduce((acc, n) => acc + Math.round(n), 0);
const offset = expectedSum - sum;
numbers.sort((a, b) => (Math.round(a) - a) - (Math.round(b) - b));
return numbers.map((n, i) => Math.round(n) + (offset > i) - (i >= (numbers.length + offset)));
}

最新更新