为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

富国沪深 2023-07-14 15:09:40
我正在寻找paxdiablo中该算法的最短、最快的纯 JavaScript 实现,以将舍入百分比添加到 100%。Value      CumulValue  CumulRounded  PrevBaseline  Need---------  ----------  ------------  ------------  ----                                  013.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
查看完整描述

2 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

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 使用 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


查看完整回答
反对 回复 2023-07-14
?
MMTTMM

TA贡献1869条经验 获得超4个赞

刚刚翻译了接受的答案中所做的事情


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

}


查看完整回答
反对 回复 2023-07-14
  • 2 回答
  • 0 关注
  • 233 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号