Public Group

Three of a kind numbers

This topic is 1989 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I am creating a method isThreeKind(int[] fiveNumbers) and it should return a boolean if 3 of the 5 are the same. I don't understand how I should go about doing this. I also need to make a similar method but instead do 4 of a kind. If someone could just help me out with understanding the logic that would be great.

Thanks

Share on other sites
One way would be look at the first number and then check the rest of the array for two or more of that number. If there aren't, look at the second number and check the rest of the array, and so on. Another way would be to sort the array first and then see if there or three or more in a row.

Share on other sites

Well, you need to test if 3 of 5 numbers are the same.

What you could do is use a nested for loop to iterate through all the numbers and test which is the same with which then have an integer keep track of how many numbers are the same, then return true if it's greater than three. That's just one possible solution. There are probably others.

Share on other sites

As you loop through the array, you don't have to go back wards, for example test the first one against the ones after it, then test the second one against the ones after it, but you don't have to retest the first one against the second since you already know the first one failed the test.  If you make it to the second to last one, ( only 2 left ) and you haven't found 3 matches yet, you don't have to test the last two since there is only 2 left there can't be 3 matches in 2 objects.

Share on other sites

ok i got it!
I sorted the array and simply checked for the number of consecutive numbers that are the same.

thanks for the help guys

Share on other sites

Why not just use a Hash?  Something like this (might be missing some corner cases):

int pair_count = 0;
bool three_of_a_kind = false;
bool four_of_a_kind = false;
for (int i=0; i<5; ++i) {
hash[cards]++;
if (hash[cards] == 2) pair_count++;
three_of_a_kind ||= hash[cards] == 3;
four_of_a_kind ||= hash[cards] == 4;
}

// now you can see if it has a two pair, a three of a kind, a four of a kind, or a full house.



Share on other sites

i dont really understand what a hash is and I would like to keep this game simple. By the way this is for a game of yahtzee not poker

here is my code just so you guys could see what I did

Arrays.sort(player1.diceValues);
for(int i = 0; i < 3; i++){
if(player1.diceValues == player1.diceValues[i + 1] && player1.diceValues == player1.diceValues[i + 2]){
player1.score =+ player1.diceValues * 3;
}
}

Edited by nitishk

1. 1
2. 2
Rutin
21
3. 3
4. 4
frob
13
5. 5

• 12
• 9
• 9
• 17
• 21
• Forum Statistics

• Total Topics
632601
• Total Posts
3007344

×