猿问

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


富国沪深
浏览 236回答 2
2回答

绝地无双

const values = [13.626332, 47.989636, 9.596008 , 28.788024];const round_to_100 = (arr) => {&nbsp; &nbsp; let output = [];&nbsp; &nbsp; let acc = 0;&nbsp; &nbsp; for(let i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; let roundedCur = Math.round(arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; const currentAcc = acc;&nbsp; &nbsp; &nbsp; &nbsp; if (acc == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.push(roundedCur);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; acc += arr[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; acc += arr[i];&nbsp; &nbsp; &nbsp; &nbsp; output.push(Math.round(acc) - Math.round(currentAcc));&nbsp; &nbsp; }&nbsp; &nbsp; return output;}console.log(round_to_100(values));我的基准和唯一的其他答案 dshung 使用 benchmark.js 的 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

MMTTMM

刚刚翻译了接受的答案中所做的事情const bar = (numbers) => {&nbsp; &nbsp; const expectedSum = 100;&nbsp; &nbsp; const sum = numbers.reduce((acc, n) => acc + Math.round(n), 0);&nbsp; &nbsp; const offset = expectedSum - sum;&nbsp; &nbsp; numbers.sort((a, b) => (Math.round(a) - a) - (Math.round(b) - b));&nbsp; &nbsp; return numbers.map((n, i) => Math.round(n) + (offset > i) - (i >= (numbers.length + offset)));}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答