Roll a die until n consecutive rolls have the same value
Show older comments
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 Comment
Adam Danz
on 19 Oct 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.
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!