Roll a die until n consecutive rolls have the same value
Mostra commenti meno recenti
Let n be a positive integer. We plan to roll a fair 6-sided die until n consecutive rolls have the same value. My task is to write a MATLAB function that approximates the expected value EV. The routine will preform NTrials trials where a trial consists of rolling the 6-sided die until n consecutive rolls have the same value, and will then calculate EV by averaging the number of rolls over all of the trials. The program I have written so far works, however I do not know how to implement the 'n consecutive rolls' into my program.
Here is what I have so far.
function EV = ex1(n,NTrials)
%
%
rng('shuffle')
TotalNRolls = 0;
for trial = 1:NTrials
die = randi(6);
lastroll = randi(6);
TotalNRolls = TotalNRolls + 2;
while die ~= lastroll
die = lastroll;
lastroll = randi(6);
TotalNRolls = TotalNRolls + 1;
end
end
EV = TotalNRolls/NTrials;
1 Commento
Adam Danz
il 19 Ott 2020
" I do not know how to implement the 'n consecutive rolls' into my program. "
I would use a while loop that ends when roll n-1 matches roll n. That could be set up in many ways. Here's one way.
isMatch = false;
previousRoll = nan;
counter = 0;
while ~isMatch
counter = counter+1;
roll = randi(6);
if roll==previousRoll
isMatch = true;
continue
else
previousRoll = roll;
end
end
or maybe you want to store each round within a vector which would be simple to implement.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Argument Definitions in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!