Looking for specific combinations in rows of a matrix

조회 수: 1 (최근 30일)
Tyler Holliday
Tyler Holliday 2019년 9월 10일
댓글: David Hill 2019년 9월 10일
I am simulating the probability of combinations in a single throw of Yahtzee dice and have been trying to figure out how to look for specific combinations without using complicated loops. For example I am looking for 4-of-a-kind with the remaining die being a different number, so not a Yahtzee.
I have code that detects a Yahtzee using a for loop and another that finds combos like 11112, 11113, etc.
%% Build Simulation Matrix
N = 1e6; % number of runs
dice = 5; % number of dice
vals = 6; % # of sides on dice
H = randi(vals,N,dice); % fill matrix
%% Initialize Counts
yahtzee = 0; % part ii
four_of_a_kind = 0; % part iii
%% Find Yahtzees (Part ii)
for rr = 1:N
if (H(rr,:)==H(rr,1)) % find all Yahtzee rolls in H by comparing
yahtzee = yahtzee + 1; % the first value to the remaining values
end % in each row
end
%% Find 4-of-a-kinds (Part iii)
for rr = 1:N
if ((H(rr,(2:end-1))==H(rr,1)))& ... % find 4-of-a-kind
((H(rr,end)~=H(rr,1)))
four_of_a_kind = four_of_a_kind + 1;
end
end
Edit: Here is the answer that worked best. Thanks again, David!
H=sort(H,2);
h=diff(H,1,2);
hh=h==0;
hhh=sum(hh,2);
yahtzee=sum(hhh==4);
four_of_a_kind=sum(ismember(hh,[1 1 1 0],'rows'))+sum(ismember(hh,[0 1 1 1],'rows'));

채택된 답변

David Hill
David Hill 2019년 9월 10일
No loops!
if unique(H)==1%yahtzee
a=diff(sort(H));
if sum(a==0)==3%4-or-a-kind
  댓글 수: 6
Tyler Holliday
Tyler Holliday 2019년 9월 10일
Thanks, David, that worked a lot better than my complicated loops. I was close to figuring it out but was struggling to properly use diff().
David Hill
David Hill 2019년 9월 10일
short_straight=sum(s==3)-sum(ismember(h,[1 2 1 1],'rows'))-sum(ismember(h,[1 2 1 1],'rows'));
pairs=sum(hhh==1)-sum(ismember(h,[0 1 1 1],'rows'))-sum(ismember(h,[1 0 1 1],'rows'))-sum(ismember(h,[1 1 0 1],'rows'))-sum(ismember(h,[1 1 1 0],'rows'));
nothing=N-yahtzee-pairs-two_pairs-three_of_kind-short_straight-long_straight-full_house-four_of_a_kind;

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Word games에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by