I am trying to write an algorithm to determine if an array of five cards contain
ID: 3625290 • Letter: I
Question
I am trying to write an algorithm to determine if an array of five cards contains three of a kind. I've pasted what I have now below, I haven't gotten very far yet. Any ideas on how to approach this would be appreciated.public boolean hasProperty(Hand cards)
{
Card[] hand = cards.getCards();
int count = 1;
for(int i = 0; i < hand.length - 1; i++)
{
for(int j = 1; j < hand.length - 2; j++)
{
for(int k = 2; j < hand.length - 3; j++)
{
if(hand[i].returnRank() == hand[j].returnRank())
{
if(hand[k].returnRank() == hand[j].returnRank())
{
count++;
}
}
}
}
}
return count == 3;
}
Explanation / Answer
I'd do it this way:
public boolean hasProperty(Hand cards)
{
Card[] hand = cards.getCards();
for(int i = 0; i < hand.length-2; i++)
{ // search for a matching card from among the cards we haven't already tested for whether they have a match
for(int j = i+1; j < hand.length-1; j++)
{
if (hand[i].returnRank() == hand[j].returnRank())
// we found two of a kind, now search for a third among the remaining cards
{
for(int k = j+1; k < hand.length; k++)
{
if(hand[k].returnRank() == hand[j].returnRank())
{
return true;
}
}
}
}
}
// our search didn't turn anything up.
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.