Reputation: 35
For a school assignment we are working on implementing the yahtzee game in java, but I am having some problems with making algorithms for the straights (small and large straight, which means 4/5 consecutive numbers for a small straight and 5/5 for a large).
I have made one algorithm that I believe should be working, but in reality it always puts out 0 so I should be missing something:
private void straights(int category) {
Arrays.sort(dices);
int nonConsecCount = 0;
for(int currDice = 0; currDice < N_DICE - 2; currDice++) {
if(dices[currDice] != dices[currDice + 1] + 1) {
nonConsecCount++;
}
}
if(nonConsecCount == 0 && category == LARGE_STRAIGHT) {
score[currPlayer - 1][category - 1] = 40;
display.updateScorecard(category, currPlayer, 40);
} else if(nonConsecCount <= 1 && category == SMALL_STRAIGHT) {
score[currPlayer - 1][category - 1] = 30;
display.updateScorecard(category, currPlayer, 30);
} else {
score[currPlayer - 1][category - 1] = 0;
display.updateScorecard(category, currPlayer, 0);
}
}
N_DICE
is equal to 5.
My theory behind this algorithm was; everytime you find a number in the (sorted) array of dicevalues that doesn't have a consecutive number as the next one, add one to the non consecutive count, and in the end check for this counter when handing out the score to the player.
Any help would we greatly appreciated!
Upvotes: 1
Views: 1853
Reputation: 7649
According to the rules of the game which I quickly skimmed through the article in the wikipedia
Small Straight - Is 4 sequential dices (30 score) that is
1,2,3,4 or 2,3,4,5 or 3,4,5,6
Large Straight - Is 5 sequential dices (40 score) that is
1,2,3,4,5 or 2,3,4,5,6
If small straight, then you should have a nonConsecCount equal to 1 because 5 - 1 is 4 and that gives us the four consecutive dices. If large straight, then you should have a nonConseCount equal to 0 because 5 - 0 gives us all five elements as consecutive.
If I understand the game correctly (taking into account the fact that I just skimmed it), you need the following modifications in your code:
Make the following changes to your code:
int nonConsecCount = 0;
for(int currDice = 0; currDice < N_DICE - 1; currDice++) {
if(dices[currDice] + 1 != dices[currDice + 1]) {
System.out.println("failed consecutive match!");
nonConsecCount++;
} else {
System.out.println("passed consecutive match for "+ dices[currDice]);
}
}
System.out.println(nonConsecCount);
I provided the above code the following dices and got nonConsecCount as show in the comment line:
int[] dices = new int[]{3,4,5,1,2};
//output 0 - this is largest straight
int[] dices = new int[]{3,4,5,6,2};
//output 0 - this is largest straight too
int[] dices = new int[]{3,4,5,2,2};
//output 1 - this is smallest straight
int[] dices = new int[]{3,4,2,2,2};
//output 2 - this is none of the two
Upvotes: 1