-1

I'm looking for the shortest and fastest pure JavaScript implementation of this algorithm from paxdiablo to add rounded percentages up to 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
Ben
  • 1,550
  • 1
  • 16
  • 24

2 Answers2

2

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

Benchmarks for mine and the only other answer dshung's bar function using 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
Khai
  • 342
  • 3
  • 7
0

Just translated what was done in the accepted answer

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)));
}
hungdoansy
  • 436
  • 4
  • 10
  • This is not really what I was looking for. But it's still helpful. Thank you! – Ben Nov 10 '20 at 22:11
  • This answer is not correct, check on some meaningful number lists, especially those whose sum doesn't yield 100 when numbers are rounded but give something like 101 or 99. The accepted answer works as opposed to this one. I don't get what was the intention here, but I assume the index is used not the way it should be actually. – Fyodor Aug 23 '23 at 11:44