Code Golf: Who has the best poker hand?

Viewed 2910

I love challenges like this, I'll hopefully submit my answer soon.

Which player has the best 7 card hand?

Given an unordered list of 9 cards (separated by a space), work out which player has the best poker hand. Here is a list of poker hand rankings. Example input:

2C 5H AS KS 2D 4D QD KH 3S
(ie: [[2C 5H] [AS KS] [2D 4D QD KH 3S]])

First 2 cards in the array represent player 1's hand, second 2 in the array represent player 2's hand. The last 5 cards represent the community cards, cards both players share. In effect, both players have 7 cards, and you must determine which player has the best 5 card poker hand.

A card is defined as a string, with the first character representing the card value, and the second value representing the suit. Always upper-case. No card may appear twice.

The function will calculate if the hand is a draw or a win to either player. It will ouput the totals at the end of the input. The output format is defined later on in this post.

Examples

2C 5H AS KS 2D 4D QD KH 3S
(ie: [[2C 5H] [AS KS] [2D 4D QD KH 3S]])
Player 2 wins this hand.  Player 1 has a pair of 2's, player 2 has a pair of kings.

5S 6S 8H 9D 7S 8S JH TS 2H
(ie: [[5S 6S] [8H 9D] [7S 8S JH TS 2H]])
Player 1 wins this hand  Player 1 has a flush, player 2 has a straight.

2S 2H AC AS 2C AH 9H TS 2D    
(ie: [[2S 2H] [AC AS] [2C AH 9H TS 2D]])
Player 1 wins this hand.  Player 1 has quads, player 2 has a full house

5S 6S 2D 4D 9S AS KD JC 9D
(ie: [[5S 6S] [2D 4D] [9S AS KD JC 9D]])
A draw.  Both players have Ace high.

More Info

Thanks to mgroves for the following link to Project Euler which has a similar problem: http://projecteuler.net/index.php?section=problems&id=54

Test Data

We will use the Project Euler test data:

http://projecteuler.net/project/poker.txt

Your solution should accept that text file as input, and output a total of wins and draws.

Example Output

Output must be in this format:

1: 45
2: 32
D: 12

Player 1 won 45 hands, player 2 won 32 hands, and there were 12 draws. (Not actual results)

Rules

  • Doesn't have to return the winning hand type, only WHO won if anyone
  • Card list input has no particular order
  • No card appears twice in the input
  • Input is always uppercase
  • Takes the Project Euler test data as an input
  • Outputs a count, of which player won the most hands and total draws in given format above
6 Answers
Related