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; endend
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'));
Best Answer