Looking for specific combinations in rows of a matrix

Asked by Tyler Holliday

Tyler Holliday (view profile)

on 10 Sep 2019
Latest activity Commented on by David Hill

David Hill (view profile)

on 10 Sep 2019
Accepted Answer by David Hill

David Hill (view profile)

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'));

Tags

Answer by David Hill

David Hill (view profile)

on 10 Sep 2019

No loops!
if unique(H)==1%yahtzee
a=diff(sort(H));
if sum(a==0)==3%4-or-a-kind

David Hill

David Hill (view profile)

on 10 Sep 2019
s=sum(h==1,2);
full_house=sum(ismember(hh,[1 1 0 1],'rows'))+sum(ismember(hh,[1 0 1 1],'rows'));
three_of_kind=sum(ismember(hh,[0 1 1 0],'rows'))+sum(ismember(hh,[1 1 0 0],'rows'))+sum(ismember(hh,[0 0 1 1],'rows'));
two_pairs=sum(ismember(hh,[1 0 0 1],'rows'))+sum(ismember(hh,[1 0 1 0],'rows'))+sum(ismember(hh,[0 1 0 1],'rows'));
long_straight=sum(s==4);
Tyler Holliday

Tyler Holliday (view profile)

on 10 Sep 2019
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 (view profile)

on 10 Sep 2019
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;