// What's the minimum number of times you have to flip a coin before you can have three consecutive flips that result in the same outcome (either all three are heads or all three are tails)? What's the maximum number of flips that might be needed? How many flips are needed on average? In this exercise we will explore these questions by creating a program that simulates several series of coin flips.
// Create a program that uses a random number generator to simulate flipping a coin several times. The simulated coin should be fair, meaning that the probability of heads is equal to the probability of tails. Your program should flip simulated coins until either 3 consecutive heads of 3 consecutive tails occur. Display an H each time the outcome is heads, and a T each time the outcome is tails, with all of the outcomes for one simulation on the same line. Then display the number of flips that were needed to reach 3 consecutive occurrences of the same outcome. When your program is run it should perform the simulation 10 times and report the average number of flips needed. Sample output is shown below:
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);
}
}
}
}
Is there any way to repeat the while loop a number of times? for example 10 times
CodePudding user response:
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))
CodePudding user response:
- Replace the
while...loop
with afor...loop
. - Use
break
to exit the loop early if your boolean variable is set to true.
See below:
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");
}
CodePudding user response:
You could keep track of how many consecutive heads or tails there have been for the previous n
flips yourself using a couple of variables and a sliding window:
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}`);
Example Output:
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