JavaScript:四舍五入百分比不得超过100%

时间:2020-11-05 16:00:07

标签: javascript algorithm performance rounding

我正在寻找this algorithmpaxdiablo最快和最快的纯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

2 个答案:

答案 0 :(得分: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的唯一其他答案

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

答案 1 :(得分:1)

只需翻译接受答案中的内容

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