In MATLAB, Given a dice with six numbers ({1, 2, 3, 4, 5, 6}), each number comes
ID: 669246 • Letter: I
Question
In MATLAB,
Given a dice with six numbers ({1, 2, 3, 4, 5, 6}), each number comes with the same probability when you roll it. Suppose you have such THREE dices and you simultaneously roll all of them to get the sum of those three output numbers. When the sum is 3 or 18, you win. Otherwise, you lose. You are so addicted to this game and will not stop until win it once (get 3 or 18 in one play). Let the random variable Y denote the number of plays when you stop playing. You have to repeat the game several times (1000) and plot the histogram of how many times did you tossed the three dice before you reached 3 or 18.
Explanation / Answer
Program1: with repeated choices
% Roll the dice "numberOfRolls" times
numberOfRolls = 200; % Number of times you roll all 3 dices.
n = 3; % Number of dices.
maxFaceValue = 6;
Y=0;%Number of Plays
f=1;
while(f==1)
if(Y>numberOfRolls)
exit(0);
end;
rolls = randi(maxFaceValue, n, numberOfRolls);
% Sum up dice values for each roll.
columnSums = sum(rolls, 1);
if(columnSums==18)
fprintf('You Win ');
break;
elseif(columnSums==3)
fprintf('You Win ');
break;
else
fprintf('You Lose ');
f=input('Do you want to continue ');% enter 0 or 1
end
Y=Y+1;
end
fprintf('Number of Plays:%f ',Y);
Program2: number of rolls 1000
% Roll the dice "numberOfRolls" times
numberOfRolls = 1000; % Number of times you roll all 3 dices.
n = 3; % Number of dices.
maxFaceValue = 6;
Y=0;%Number of Plays
while(Y<=numberOfRolls)
rolls = ceil(randi(maxFaceValue, n, numberOfRolls));
% Sum up dice values for each roll.
columnSums = sum(rolls, 1);
fprintf('%d ',columnSums);
if(columnSums==18)
fprintf('You Win ');
break;
elseif(columnSums==3)
fprintf('You Win ');
break;
else
fprintf('You Lose ');
end
Y=Y+1;
end
fprintf('Number of Plays:%f ',Y);
% Find out how many times each sum occurred.
edges = min(columnSums):max(columnSums);
counts = histc(columnSums, edges);
% Normalize
grandTotalSum = sum(counts(:));
normalizedCountSums = counts / grandTotalSum;
bar(edges, normalizedCountSums, 'BarWidth', 1);
grid on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
title('Frequency of Roll Sums', 'FontSize', 40);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.