Can someone help me understand this code?

1 view (last 30 days)
David Deman
David Deman on 7 Dec 2021
Answered: Chunru on 7 Dec 2021
throwAgain=MCO_throwAgain()
function throwAgain=MCO_throwAgain()
die=1;
%Random number 1-6 of a 1x6 vector
RV=randi([1,6],1,6);
flag=0;
while(1)
for i=1:6
if(sum(RV==i)>=5)
flag=1;
break;
end
end
if(flag==1)
break;
end
die=die+1;
RV=randi([1,6],1,6);
end
throwAgain=die;
end
Thank you!

Answers (2)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh on 7 Dec 2021
function throwAgain=MCO_throwAgain()
define a function named MCO_thorAgain with no input and one output as throwAgain
die=1;
define and set the die vairable to 1 (as a scalar variable)
RV=randi([1,6],1,6);
create an 1x6 Array with integer random numbers between 1 and 6.
flag=0;
define and set the flag vairable to 0 (as a logical vairable)
while 1
will start a while loop and the condition is always true. but in code there is a flag which become 1 and the while loop breaks.
for i=1:6
if(sum(RV==i)>=5)
flag=1;
break;
end
end
in each loop the code check for every number between 1 to 6, if number of random numbers in RV which are equal to number i (each number) is greater or equal to 5. in other word the code check if 5 or 6 number of RV is same. so if it is the flag become 1 and the for-loop breaks.
if(flag==1)
break;
end
die=die+1;
RV=randi([1,6],1,6);
end % end of while
after for-loop ends, the code check if flag is 1. if it is the while loop breaks. if it isn't the scalar die increased by 1 value and RV become new random integer numbers. and while loop continue.
throwAgain=die;
end % end of function
when while loop end. the output of function become the die variable.
which means the output of function is number of times the random integer created but it does not have 5 or 6 same value in it. (first time in loop that RV has 5 or 6 same value the flag become 1 and loop breaks.
throwAgain=MCO_throwAgain()
this line just call the function to execute.

Chunru
Chunru on 7 Dec 2021
[throwAgain, RV]=MCO_throwAgain()
throwAgain = 35
RV = 1×6
4 4 4 4 4 1
function [throwAgain, RV]=MCO_throwAgain()
% MCO_throwAgain outputs the number of random throws taken to have at least 5 same
% die points out of 6 dies. Optionally it also outputs the final throw
% points.
die=1; % 1st throw
%Random number 1-6 of a 1x6 vector
RV=randi([1,6],1,6); % throw of 6 dies
flag=0; % at least 5 same points
while(1) % keep trying
% check if at least 5 dies have same point
for i=1:6
if(sum(RV==i)>=5)
flag=1;
break;
end
end
% if yes, stop
if(flag==1)
break;
end
% Otherwise, throw again
die=die+1;
RV=randi([1,6],1,6);
end
throwAgain=die; % retrurn the number of trials
end

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by