Coding Kata – January 29 2010 – Playing Vegas

1.29.2010 | Kata

Goal: Design and implement an algorithm to detect certain hands in a game of Poker. You are given your parameters as 5 ints [0-13] representing each value of the card. The hands to check are:

  • Four of a kind (ex: 5,4,5,5,5)
  • Full house (ex: 5,4,4,5,5)
  • Three of a kind (ex: 5,4,5,5,1)
  • Two pair (ex: 8,4,4,5,5)
  • Pair (ex: 7,1,2,5,5)
  • High card (ex: 1,2,3,4,5)

Constraints:

  • Return the String value or enum code (to your specification) representing each case

Hmmm of the day: Are there any poker hands which could fall into more than one category?


Responses

Kevin Kuchta
1.30.2010

Heh, fun story- I got this question when I was interviewing in Redmond. I got an answer, but it wasn’t very elegant. I’ve got a few minutes, let’s see if I can do better.

Kevin Kuchta
1.31.2010

Well, I got distracted by food last night, so I put this together this morning. It’s pseudo-code-tastic.

detectHand(int[] hand)

//Do the first half of a counting sort
int[] countedHand = new int[13]
for each card in hand
countedHand[hand]++

//Go through each element in the counted array
boolean foundThree=false
boolean foundTwo=false
for each count in countedHand
if( count == 4)
return “Four of a kind”
else if( (foundThree && count == 2) || (foundTwo && count == 3) )
return “Full house”
else if( foundTwo && count == 2 )
return “Two of a kind”
else if( count == 3 )
foundTwo = false
else if( count == 2 )
foundTwo = true
end
end
if(foundThree)
return “Three of a kind”
else if(foundTwo)
return “Pair”
else
return “High Card”
end
end

Chris
1.31.2010

Quite right you are! I did pull this from my MS interview, but hey, interesting to see we both got it. You also got the catch!

This is also the most efficient algorithm too, nice work! :)

Chris
1.31.2010

Or rather, it’s the most efficient that I’ve stumbled across/come up with ;)

Comments