我不确定计算这个公式的正确术语是什么;所以我很抱歉,如果标题看起来有点模糊的话。
我的问题涉及在JavaScript中对公式进行编程;但是,为了简化目标,适用以下场景:
想象一下我的面包店有无限数量的馅饼。所以我宣传说,任何人都可以走进来,免费拿个馅饼;因此,不确定数量的人开始来到我的面包店,收集一个免费的馅饼。
在数量仍然无限的情况下,我决定,在所有收集馅饼的人中(不确定的人数量--可能是1,2,3,甚至1000000人),我想让70%的人得到蓝莓派,而其他30%的人得到苹果派。
我如何在不知道收集馅饼的人数量的情况下计算百分比分配呢?
我的思维过程是,我会给每个人一个蓝莓派,直到有7个人已经收集了一个蓝莓派。接下来的三个人,他们会得到一个苹果派。
但是如果(为了争论的缘故),总共只有9个人来到我的面包店呢?所有9个人都会得到蓝莓派,而没有人会得到苹果派?
更让人困惑的是(不需要,仅仅用线性/非随机的方法来计算速度):如果我不想看起来太明显,并且以相同的速度(70/30)随机分配馅饼,那该怎么办?(A =蓝莓派,B=苹果派):
因此,与其:
A,A,A,A,A,A,A,B,B,B
最好是:
A,A,B,A,B,B,A,A,A,A
此外,指这类公式的正确术语/名称是什么?
发布于 2022-08-18 16:14:03
如果你想要的数字只是基于概率( 70 %和30%)不喜欢,每100人确切70人(70%)必须得到蓝莓和其他30人苹果派(意为72和28不!!)下面是一个简单的解决方案:
最简单的方法是使用Math.random()
(它给出一个从0到0.9的随机数字,例如: 0.2374、0.6789、0。。。。。但从来没有。首先得到Math.random()
并乘以10,然后使用Math.floor()
使它成为整数。然后,如果你得到从0到6 (0,1,2,3,4,5和6)的任何数字,给蓝莓,其他(7,8和9)给苹果派。
const array = []
// Make a for Loop for N number of peoples
for (i=0; i<100; i++){
let pies;
// Get a whole random number (0 to 9)
let randomN= Math.floor(Math.random() * 10)
// Write the probabilities
if (randomN == 0) pies = "Apie"
else if (randomN == 1) pies = "Apie"
else if (randomN == 2) pies = "Apie"
else pies = "Bpie"
//Make a list with array
array.push(pies);
}
// Let's check the results
function arrayEcounter(array) {
let Apie = 0;
let Bpie = 0;
for ( i= array.length-1; i >= 0; i--) {
if (array[i] == "Apie") Apie += 1;
else if (array[i] == "Bpie") Bpie += 1;
}
return `${Apie} people got Apple pie
and ${Bpie} people got Blueberry pie.
You have gave away total ${Apie+Bpie} pies`
}
console.log(arrayEcounter(array))
CONSOLE 27人吃苹果派,73人买蓝莓派。你总共送了100个馅饼
300276人吃苹果派,699724人吃蓝莓派。你总共给了1000000个馅饼
发布于 2022-08-18 16:42:57
因为你知道百分比分布,实际的人数是无关紧要的。但是,你确实需要知道每x个人要“准备”多少馅饼,这样你就可以随机地把派A分配给派B。
function CreatePieDistribution(applePercentage, perNPeople) {
let numApplePiesPerNPeople = perNPeople * applePercentage;
for (let i = 0; i < perNPeople; i++) {
pies.push( createPie(i, numApplePiesPerNPeople));
}
pies.sort((a, b) => a.sortby - b.sortby);
}
function createPie(pId, numApplePies) {
let pie = {
id: pId,
type: null,
sortby: null
};
if (pId < numApplePies)
pie.type = "apple"
else
pie.type = "blueberry"
pie.sortby = Math.random();
return pie;
}
let pies = [];
let pctApple = .3;
let batchSize = 10;
CreatePieDistribution(pctApple, batchSize)
console.log(pies);
https://stackoverflow.com/questions/73400182
复制相似问题