箱子装了100个鸡蛋,可能有坏蛋甚至全坏了,已经挑出了个坏的,再挑个还是坏的概率多大?
Kimi
Kimi
Gemini
Gemini
GPT推理
GPT推理
JS验证代码:
let okCount = 0;
let drawnCount = 0;
const eggCount = 100;//100蛋(对应101个盒子)
const initialEggs = [...Array(eggCount).fill('好蛋'), ...Array(eggCount).fill('坏蛋')].join(',');
const boxes = Array.from({ length: eggCount + 1 }, (_, index) => {
const goodEggsCount = eggCount - index;
return initialEggs.split(',').slice(0, eggCount).map((_, eggIndex) => eggIndex < goodEggsCount ? '好蛋' : '坏蛋');
});//boxes 中有所有蛋的可能性
const want = Math.random() < 0.5 ? "好蛋" : "坏蛋";//随机想要好蛋还是坏蛋(概率一样)
for (let i = 0; i < 1000000; i++) {
// 随机选盒
const chosenBox = boxes[Math.floor(Math.random() * boxes.length)];
const firstIndex = Math.floor(Math.random() * chosenBox.length);
if (chosenBox[firstIndex] === want) {
drawnCount++;//找到了第一个想要的蛋
let secondIndex;
do {//找第二个蛋,位置要不一样
secondIndex = Math.floor(Math.random() * chosenBox.length);
} while (secondIndex === firstIndex);
if(chosenBox[secondIndex] === want)
okCount++;//连续找到了想要的蛋
}
}
const probability = okCount / drawnCount * 100;// 计算概率
console.log(`总共抽取 ${drawnCount} 组蛋, 其中 ${okCount} 组两个都是${want}`);
console.log(`概率为: ${(probability).toFixed(2)}%`);
运行结果:
总共抽取 498890 组蛋, 其中 332604 组两个都是坏蛋
概率为: 66.67%
结果确实是三分之二