【问题标题】:JavaScript: Add rounded percentages up to 100 %JavaScript:将四舍五入的百分比添加到 100 %
【发布时间】:2021-02-18 08:55:39
【问题描述】:
我正在从paxdiablo 中寻找this algorithm 的最短和最快的纯 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
【问题讨论】:
标签:
javascript
algorithm
performance
rounding
【解决方案1】:
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));
我的基准测试和使用 benchmark.js 的唯一其他答案 dshung 的 bar 函数
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
【解决方案2】:
刚刚翻译了接受的答案中所做的事情
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)));
}