-
yhatzee, small straight
Howdy. I have written a small yhatzee clone game, (i realized i love this game when i got the handheld version for my graduation ). Anyways, How would y'all go about detecting a small straight. If you don't know yhatzee, you roll five dice, and a small straight is when four of those dice are numerically sequential (ie: 3,4,5,6 or 2,3,4,5). I have the values stored into an array of size five, and sorted from lowest to highest in value. Some examples to think about are (1,2,3,3,4) or (1,3,4,5,6) or one that isn't a small straight (1,2,3,3,6). If all you have is tips, thanks.
-
This was a pretty interesting problem.. so I solved it. Hopefully the solution is readable, and works in all cases, and although I think it is both, I can't guarentee it is either:).
Code:
#include <iostream>
bool isSmallStraight(int sortedDice[5]) {
int curSeqLen=1;
int lastDie=sortedDice[0];
// if the lowest number is a 4, or the highest number is a 3, it cannot be small straight
if (sortedDice[0] >= 4 || sortedDice[4] <= 3) return false;
// iterate through the dice
for (int i = 1; i < 5; i++) {
// the current die is one greater than the last one, the numbers are in sequence
if (sortedDice[i] == lastDie+1) {
curSeqLen++;
}
// the current die is the same as the last die, nothing is needed to be done
// as i will be incremened in the for loop... so this can go, but it makes
// the code easier to understand, IMO
else if (sortedDice[i] == lastDie) {
// the consecutive dice are not in order, still might be a straight in there though
// like in the case that i is small when this is reached, ex. {1, 3, 4, 5,6 }
} else {
curSeqLen=1;
}
// obviously, a small straight is true when the sequence is 4 or longer
if (curSeqLen >=4) return true;
lastDie = sortedDice[i];
}
// reached the end of the dice, and no sequence has been greater than 4 long, must not be a small straight
return false;
}
void test(int sortedDice[5]) {
for (int i = 0; i < 5; i++) {
std::cout << sortedDice[i] << ' ';
}
if (isSmallStraight(sortedDice)) {
std::cout << "\tTrue... the sequence is a small straight" << std::endl;
} else {
std::cout << "\tFalse.. the sequence is NOT a small straight" << std::endl;
}
}
int main() {
int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 3, 4, 4, 4, 6 };
int c[5] = { 2, 3, 4, 5, 5 };
int d[5] = { 1, 1, 1, 4, 5 };
test(a); test(b); test(c); test(d);
return 0;
}
-
Wow, thanks for the fast and well thought out help. Now, to work in some graphics...