function allocateByRatio(total, ratios) {
const sumRatios = ratios.reduce((acc, curr) => acc + curr, 0);
const allocated = [];
for (let i = 0; i < ratios.length; i++) {
const ratio = ratios[i];
const value = Math.floor((total * ratio) / sumRatios);
allocated.push(value);
}
let remainder = total - allocated.reduce((acc, curr) => acc + curr, 0);
for (let i = 0; i < remainder; i++) {
allocated[i % allocated.length]++;
}
return allocated;
}
这个函数接收两个参数:总数 total
和比例数组 ratios
。在函数内部,我们先计算比例数组中所有元素的总和 sumRatios
。然后使用一个循环来遍历比例数组,计算出每个比例对应的分配值,并将这些值存储在一个数组 allocated
中。
接下来,我们计算总数与所有分配值之间的差值,将这个差值按照轮询的方式加到 allocated
数组中的每个元素中,直到差值为 0。
最后,我们返回分配值数组 allocated
。这个函数的关键在于按比例计算每个值的过程,我们使用了 Math.floor
函数来确保分配的值是整数,并避免了由于除法带来的小数误差。