Summing up Dice in MATLAB

2019-02-26 04:10发布

问题:

My function called RollDice simulates the rolling of a given number of six sided dice a given number of times. The function has two input arguments, the number of dice (NumDice) that will be rolled in each experiment and the total number (NumRolls) of times that the dice will be rolled. The output of the function will be a vector SumDice of length NumRolls that contains the sum of the dice values in each experiment.

This is my code right now: how do I account for the SUM of the dice? Thanks!

function SumDice= RollDice(NumDice,NumRolls)

FACES= 6;               
maxOut= FACES*NumDice;         
count= zeros(1,maxOut);  


for i = 1:NumRolls

    outcome= 0;  
    for k= 1:NumDice
        outcome= outcome + ceil(ranNumDice(1)*FACES);
    end

    count(outcome)= count(outcome) + 1;
end


bar(NumDice:maxOut, count(NumDice:length(count)));
message= sprintf('% NumDice rolls of % NumDice fair dice',  NumRolls, NumDice);
title(message);
xlabel('sum of dice values');  ylabel('Count');

回答1:

This is a simple and neat little problem (+1) and I enjoyed looking into it :-)

There were quite a few areas where I felt I could improve on your function. Rather than going through them one by one, I thought I'd just re-write the function how I'd do it, and we could go from there. I've written it as a script, but it can be turned into a function easily enough. Finally, I also generalized it a bit by allowing for the dice to have any number of faces (6 or otherwise). So, here it is:

%#Define the parameters
NumDice = 2;
NumFace = 6;
NumRoll = 50;

%#Generate the rolls and obtain the sum of the rolls
AllRoll = randi(NumFace, NumRoll, NumDice);
SumRoll = sum(AllRoll, 2);

%#Determine the bins for the histogram
Bins = (NumDice:NumFace * NumDice)';

%#Build the histogram
hist(SumRoll, Bins);
title(sprintf('Histogram generated from %d rolls of %d %d-sided dice', NumRoll, NumDice, NumFace));
xlabel(sprintf('Sum of %d dice', NumDice));
ylabel('Count');

I suggest you have a close look at my code and the documentation for each function I've used. The exercise may prove useful for you when tackling other problems in Matlab in the future. Once you've done that, if there is anything you don't understand, then please let me know in a comment and I'll try to help. Cheers!

ps, If you don't ever need to refer to the individual rolls again, you can of course convert the AllRoll and SumRoll line into a one-liner, ie: SumRoll = sum(randi(NumFace, NumRoll, NumDice), 2);. I think the two-liner is more readable personally, and I doubt it will make much difference to the efficiency of the code.



标签: matlab dice