Can anyone help me fix my large straight Yahtzee function in MATLAB?
Show older comments
It works when I enter stuff like dice = [1 5 2 4 3], but if it stops working when I have any repeated numbers like dice = [1 5 2 4 1]...
function score = score_lg_straight(dice)
sorted = sort(dice);
iters = 0;
%Check neighboring dice
for rolls = 1:4
if sorted(rolls)+1 == sorted(rolls+1)
iters = iters + 1;
end
end
if iters == 4
%Score for a large straight is just 40
score = 40;
else
score = 0;
end
end
2 Comments
Walter Roberson
on 1 Jun 2018
That code is okay as far as it goes, except for the fact that it has an extra "end" at the bottom.
n
on 1 Jun 2018
Answers (1)
John D'Errico
on 1 Jun 2018
As I recall, a large straight in that game is one of two cases:
the sequence [1 2 3 4 5], OR the sequence [2 3 4 5 6]. So if you need to test for that event? This will work:
sorted = sort(dice);
if all(ismember(1:5,sorted)) || all(ismember(2:6,sorted))
score = 40;
else
score = 0;
end
Are there other ways to test for that event? Here is a cute one:
if all(diff(sorted) == 1)
score = 40;
else
score = 0;
end
How about this one?
if (numel(unique(dice)) == 5) && ismember(sum(dice),[15,20])
Categories
Find more on Word games in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!