2 回答

TA貢獻(xiàn)1946條經(jīng)驗 獲得超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));
我的基準(zhǔn)和唯一的其他答案 dshung 使用 benchmark.js 的 bar 函數(shù)
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

TA貢獻(xiàn)1869條經(jīng)驗 獲得超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)));
}
添加回答
舉報