假设我有 8 个人和5000 个苹果。
我想将所有苹果分发给所有 8 个人,这样我就没有苹果了。
但每个人都应该得到不同数量
将它们全部分发出去的最佳方式是什么?
我是这样开始的:
let people = 8
let apples = 5000
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
while (people--) {
// last person get the rest
let x = people ? getRandomInt(0, apples) : apples
// subtract how many apples i got left
apples -= x
console.log(`Giving person ${people + 1} ${x} apples (got ${apples} left)`)
}
但我不喜欢的是,最后一个人得到的苹果很少(有时少于 5 个苹果),而第一个人得到的苹果比其他人多得多
最佳答案
如果您每次都需要随机但“平衡”的结果,则需要优先考虑平衡或随机性。以下是遵循“widestGap”要求的一种可能的解决方案:
function randomDeltas(length, widestGap, remToGet) {
// widestGap >= length * 2 - 1
let deltas = [];
let sum = 0;
let start = 0;
let origLength = length;
while (length--) {
start += 1 + Math.floor(Math.random() * widestGap);
deltas.push(start);
sum += start;
}
let rem = sum % origLength;
let correction = remToGet - rem;
if (correction !== 0) {
sum -= deltas[0];
deltas[0] += correction;
if (deltas[0] >= deltas[1]) {
deltas[0] -= origLength;
}
else if (deltas[0] < deltas[1] - widestGap) {
deltas[0] += origLength;
}
sum += deltas[0];
}
return {
deltas,
sum
};
}
function randomDistinctDistribute(apples, people) {
let rem = apples % people;
let { deltas, sum } = randomDeltas(people, people * 2 - 1, rem);
let div = (apples - sum) / people;
let distribution = [];
while (deltas.length) {
distribution.push(div + deltas.shift());
}
return distribution;
}
console.log(randomDistinctDistribute(5000, 8));
console.log(randomDistinctDistribute(2500, 6));
这里的想法是随机化增量(以确保差距永远不会变大),然后将这些增量应用到除数。
<小时/>这是获得具有不同值的平衡分布的原始(确定性)方法:
function distinctDividents(apples, people) {
let distribution = [];
let div = Math.floor(apples / people);
let rem = apples % people;
if (people % 2) {
distribution.push(div);
people--;
}
let half = people / 2;
let i = 1;
while (i <= half) {
distribution.push(div - i);
distribution.unshift(div + i);
i++;
}
if (rem) {
distribution[0] += rem;
}
return distribution;
}
console.log(distinctDividents(5000, 8));
关于javascript - 分配/分发随机数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530433/