假设我有 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个苹果),第一个人比其他人更多
答案 0 :(得分:1)
如果你需要随机而且平衡的'结果每次,你需要优先考虑平衡 - 或随机性。这是您的最大差距之后的一个可能的解决方案'要求:
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));
&#13;
这里的想法是随机化增量(以确保差距永远不会变大),然后将这些增量应用于除数。
这是使用不同值进行均衡分配的原始(确定性)方法:
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));
答案 1 :(得分:0)
想想我弄明白了。只是一个小小的推文。
let x = people ? getRandomInt(0, Math.floor(apples / people)) : apples
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, Math.floor(apples / people)) : apples
// subtract how many apples i got left
apples -= x
console.log(`Giving person ${people + 1} ${x} apples (got ${apples} left)`)
}
然而,没有人会少于100个苹果或者超过1000个,但这样做会。否则它会变得更复杂。第二天,我可能只有2500个苹果和6个人......