Rolling a Fair 6-Sided Die Until Two Consecutive Rolls Have the Same Value

조회 수: 3 (최근 30일)
Sophie Culhane
Sophie Culhane 2020년 10월 2일
댓글: Sophie Culhane 2020년 10월 5일
My task is to simulate rolling a fair 6-sided die until two consecutive rolls have the same value and write a function that approximates the expected value EV. I believe I have most of the program figured out until I reach 'same number' in which I get lost. Please help me find out what to put in place of 'same number' to get my program to work. Here is my block of code:
function EV = hw20(NTrials)
%
%
rng('shuffle)
TotalNRolls = 0;
for Trial = 1:NTrials
die = randi(6);
TotalNRolls = TotalNRolls + 1;
while die == 'same number'
TotalNRolls = TotalNRolls + 1;
end
end
EV = TotalNRolls/NTrials;

답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 10월 2일
편집: Ameer Hamza 2020년 10월 2일
Try this code
function EV = hw20(NTrials)
%
%
rng('shuffle')
TotalNRolls = 1;
last_die = inf; % any number other then 1 to 6
while true
die = randi(6);
if die == last_die || TotalNRolls==NTrials
break;
else
last_die = die;
end
TotalNRolls = TotalNRolls + 1;
end
EV = TotalNRolls/NTrials;
end
  댓글 수: 3
Ameer Hamza
Ameer Hamza 2020년 10월 2일
Thanks, Steven. Your approach also makes sense for this problem. It is just my guess that NTrials is the maximum number of trials.
Sophie Culhane
Sophie Culhane 2020년 10월 5일
We have not yet learned 'break' therefore I cannot use that in my program. Thank you for the responses so far.

댓글을 달려면 로그인하십시오.


Alan Stevens
Alan Stevens 2020년 10월 2일
I think the above will produce a probability, rather than an expected value. Try
NTrials = 1000;
N = zeros(NTrials,1);
for Trial = 1:NTrials
TotalNRolls = 1;
die = randi(6);
keepgoing = true;
while keepgoing == true
oldie = die;
die = randi(6);
if die == oldie
keepgoing = false;
end
TotalNRolls = TotalNRolls + 1;
end
N(Trial) = TotalNRolls;
end
EV = sum(N)/NTrials;

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by