// 在连续三次抛硬币产生相同结果(三个都是正面或三个都是反面)之前,您必须掷硬币的最少次数是多少?可能需要的最大翻转次数是多少?平均需要翻转多少次?在本练习中,我们将通过创建一个模拟多个掷硬币系列的程序来探索这些问题。
// 创建一个程序,使用随机数生成器来模拟掷硬币几次。模拟硬币应该是公平的,这意味着正面的概率等于反面的概率。您的程序应该翻转模拟硬币,直到出现 3 个连续的正面和 3 个连续的反面。每次结果为正面时显示 H,每次结果为反面时显示 T,一次模拟的所有结果在同一行上。然后显示达到 3 次连续出现相同结果所需的翻转次数。当您的程序运行时,它应该执行 10 次模拟并报告所需的平均翻转次数。示例输出如下所示:
const headsOrTails = [];
const flipcounts = [];
let threeInARow = false;
while (threeInARow == false) {
const coinFlip = Math.floor(Math.random() * 10 + 1);
if (coinFlip <= 5) {
headsOrTails.push('H');
} else {
headsOrTails.push('T');
}
for (let index = 0; index < headsOrTails.length; index++) {
const element = headsOrTails[index];
if (element == headsOrTails[index + 1]) {
if (element == headsOrTails[index + 2]) {
threeInARow = true;
console.log('il numero di flip ottenuti è ' + headsOrTails.length);
}
}
}
}
有没有办法多次重复while循环?例如 10 次
回答1
flips = [];
for (let i = 0; i < 10; i++) {
let threeInARow = false;
let results = "";
while (threeInARow == false) {
const coinFlip = Math.random();
results += coinFlip < 0.5 ? "H" : "T";
if (results.includes("HHH") || results.includes("TTT")) {
threeInARow = true;
console.log(results);
flips.push(results.length);
}
}
}
console.log(flips);
const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
console.log("Average:", average(flips))
回答2
- 将
while...loop
替换为for...loop
。 - 如果布尔变量设置为 true,请使用
break
提前退出循环。
见下文:
const headsOrTails = [];
const flipcounts = [];
let threeInARow = false;
for(let i=0; i<10; i++)
{
const coinFlip = Math.floor(Math.random() * 10 + 1);
if (coinFlip <= 5) {
headsOrTails.push('H');
} else {
headsOrTails.push('T');
}
for (let index = 0; index < headsOrTails.length; index++) {
const element = headsOrTails[index];
if (element == headsOrTails[index + 1]) {
if (element == headsOrTails[index + 2]) {
console.log('the number of flips obtained is ' + headsOrTails.length);
threeInARow = true;
}
}
}
if(threeInARow)
break;
}
if(!threeInARow)
{
console.log("No matches were found");
}
回答3
您可以使用几个变量和一个滑动窗口来跟踪之前的 n
翻转有多少连续的正面或反面:
const flipCoin = () => Math.random() < 0.5 ? "H" : "T";
const flipCoinUntilNConsecutive = n => {
const flips = [], slidingWindow = [];
let windowHeadsCount = 0, windowTailsCount = 0;
while (true) {
const newestFlip = flipCoin();
flips.push(newestFlip);
slidingWindow.push(newestFlip);
newestFlip == "H" ? windowHeadsCount++ : windowTailsCount++;
if (slidingWindow.length == n) { // array.length is O(1).
if (windowHeadsCount == n || windowTailsCount == n) {
console.log(...flips);
return flips.length;
}
const oldestFlip = slidingWindow.shift();
oldestFlip == "H" ? windowHeadsCount-- : windowTailsCount--;
}
}
};
const n = 3, repeats = 10;
console.log(`${repeats} simulations of flipping a coin until ${n} consecutive:`);
console.log();
let minFlipsRequired = Number.MAX_VALUE, maxFlipsRequired = 0, totalFlipsRequired = 0;
for (let s = 1; s <= repeats; s++) {
const flipsRequired = flipCoinUntilNConsecutive(n);
console.log(`Simulation ${s}: ${flipsRequired}`);
minFlipsRequired = Math.min(minFlipsRequired, flipsRequired);
maxFlipsRequired = Math.max(maxFlipsRequired, flipsRequired);
totalFlipsRequired += flipsRequired;
}
console.log();
console.log(`minFlipsRequired: ${minFlipsRequired}`);
console.log(`maxFlipsRequired: ${maxFlipsRequired}`);
console.log(`totalFlipsRequired: ${totalFlipsRequired}`);
const averageFlipsRequired = totalFlipsRequired / repeats;
console.log(`averageFlipsRequired: ${averageFlipsRequired}`);
示例输出:
10 simulations of flipping a coin until 3 consecutive:
H T H T T T
Simulation 1: 6
T T H H H
Simulation 2: 5
H H H
Simulation 3: 3
H H H
Simulation 4: 3
H T H H H
Simulation 5: 5
T H H T T H H H
Simulation 6: 8
H T H T H H H
Simulation 7: 7
H T T T
Simulation 8: 4
T H T T T
Simulation 9: 5
H H H
Simulation 10: 3
minFlipsRequired: 3
maxFlipsRequired: 8
totalFlipsRequired: 49
averageFlipsRequired: 4.9