Rolling 5 dice probability

조회 수: 3 (최근 30일)
Nicholas Greiwe
Nicholas Greiwe 2015년 10월 1일
편집: John D'Errico 2015년 10월 1일
I am having trouble trying to figure out what the next step is. I have 5 dice and im trying to figure out the probability of rolling no pair, pair, three of a kind, four of a kind, and five of a kind. This is my code so far. I put the sort command to sort it in ascending order but it does not do it. Where do I go from here. Ignore the if true thing thats not in my code.
home
clear
five=0;
four=0;
three=0;
two=0;
none=0;
fh=0;
prob=zeros(1,6);
rolls=input('how many times to roll?;');
for rollnum=1:rolls
roll(:,rollnum)=randi([1 6],[1 5]);
rolls=sort(rolls);
end

답변 (2개)

John D'Errico
John D'Errico 2015년 10월 1일
편집: John D'Errico 2015년 10월 1일
Yes, I know that this answer is probably unacceptable for a homework assignment, because it is heavily vectorized. But you can still learn from such a solution.
The simple answer (for n rolls) is:
n = 1e6;
allrolls = randi([1,6],[n,5]);
norepsprob = sum(all(diff(sort(allrolls,2),[],2) > 0,2))/n
norepsprob =
0.092634
As a test, lets try a larger value of n.
n = 1e7;
allrolls = randi([1,6],[n,5]);
norepsprob = sum(all(diff(sort(allrolls,2),[],2) > 0,2))/n
norepsprob =
0.092614
If you want, break down that line where I compute the probability estimate, and see what it does. Think about why it works. Start at the middle, and work out.
That is, this sorts the rolls.
sort(allrolls,2)
Then we form a difference.
diff(sort(allrolls,2),[],2)
and test if those differences are positive (non-zero, since they are sorted.)
diff(sort(allrolls,2),[],2) > 0
Then I test if all of them are non-zero.
all(diff(sort(allrolls,2),[],2) > 0)
And then count how many were entirely non-zero, and divide by the sample size.
sum(all(diff(sort(allrolls,2),[],2) > 0))/n
Learn to think in terms of arrays and vectors. Think in terms of operations that can be done on an entire array of numbers at once. This is how you advantage the power of a tool like MATLAB. Loops will only get you so far.

Walter Roberson
Walter Roberson 2015년 10월 1일
rolls=sort(rolls);
is taking the scalar that is the number of rolls to make, sorting the scalar, and writing the sorted value back to the same variable.
You could consider sorting your roll array, after the rolls have all been made.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by