I am trying to build a die roller, for a groupe of people, that says which of 5 people has gotten the 6. Right now the die roller tells how many rolls where made. I want it to tell which of the five persons (who roll out of turn) made the roll. So if the roll number (called i) is greater then 5 (number of players) we need to subtract 5 until it is. And then display which person made the roll and how many total rolls were made.
Code die roller:
i=0; % number of throws
while 1
i = i + 1;
dieRoll = randi(6); % gives a random number 1-6
if dieRoll < 6;
continue % continue if it's not a 6
else
break % break if it is
end
end
disp(i) %display number of throws
I have then tried to implicate an other if else statement, but out of luck:
if i > 5
while i > 5
i=i-5;
end
else
i=i
end

 Réponse acceptée

Geoff Hayes
Geoff Hayes le 4 Jan 2017

0 votes

Mads - I think that your logic could be simplified to
i = i + 1;
if i > 5
i = 1;
end
So if the roll is six, then we reset to one to indicate that player one is rolling.
You may also want to consider renaming this variable to indicate what it actually represents (i.e the playerId) and to avoid confusion with the imaginary number (which MATLAB represents using i and j).

Plus de réponses (3)

Mads Emil Engmarksgaard
Mads Emil Engmarksgaard le 5 Jan 2017

0 votes

Works like a charm.
i=0; % number of throws
while 1
i = i + 1;
if i > 5
i = 1;
end
dieRoll = randi(6); % gives a random number 1-6
if dieRoll < 6;
continue % continue if it's not a 6
else
break % break if it is
end
end
x= [' Player number ', num2str(i), ' rolled a six '];
disp(x) %display
Image Analyst
Image Analyst le 5 Jan 2017

0 votes

So complicated. Why not simply make and check all the rolls at once:
% Define parameters.
numRolls = 100
numPeople = 5;
% Make all the rolls in one call to randi.
rolls = randi(6, numRolls, numPeople)
% Done. Now report who got a 6 at each roll
for roll = 1 : numRolls
whoGot6 = find(rolls(roll, :) == 6);
fprintf('\nIn roll #%d, these users got a 6: ', roll);
fprintf('%d ', whoGot6);
end
Jos (10584)
Jos (10584) le 5 Jan 2017

0 votes

A trick is to start counting from 0 and use the function REM or MOD to determine the index
numRolls = 1 ;
while (randi(6) ~= 6)
% loop until a roll was a 6
numRolls = numRolls + 1 ;
end
WhoRolled6 = rem(numRolls-1, 5) + 1 % subtract 1 to count from 0

Community Treasure Hunt

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

Start Hunting!

Translated by