Project Euler Problem 54 Solution
Question
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
 High Card: Highest value card.
 One Pair: Two cards of the same value.
 Two Pairs: Two different pairs.
 Three of a Kind: Three cards of the same value.
 Straight: All cards are consecutive values.
 Flush: All cards of the same suit.
 Full House: Three of a kind and a pair.
 Four of a Kind: Four cards of the same value.
 Straight Flush: All cards are consecutive values of same suit.
 Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
Consider the following five hands dealt to two players:
Hand  Player 1  Player 2  Winner  
1 
5H 5C 6S 7S KD
Pair of Fives

2C 3S 8S 8D TD
Pair of Eights

Player 2  
2 
5D 8C 9S JS AC
Highest card Ace

2C 5C 7D 8S QH
Highest card Queen

Player 1  
3 
2D 9C AS AH AC
Three Aces

3D 6D 7D TD QD
Flush with Diamonds

Player 2  
4 
4D 6S 9H QH QC
Pair of Queens
Highest card Nine 
3D 6D 7H QD QS
Pair of Queens
Highest card Seven 
Player 1  
5 
2H 2D 4C 4D 4S
Full House
With Three Fours 
3C 3D 3S 9S 9D
Full House
with Three Threes 
Player 1 
The file, poker.txt, contains onethousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1’s cards and the last five are Player 2’s cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player’s hand is in no specific order, and in each hand there is a clear winner.
How many hands does Player 1 win?
Haskell
import Data.Char (digitToInt)
import Data.List (nub, sortBy)
rankValue :: Char > Int
rankValue 'A' = 14
rankValue 'K' = 13
rankValue 'Q' = 12
rankValue 'J' = 11
rankValue 'T' = 10
rankValue c = digitToInt c
parse :: String > [([(Int, Char)], [(Int, Char)])]
parse str = [(parse' left, parse' right)  line < lines str,
let cards = words line,
let (left, right) = splitAt 5 cards]
where parse' cards = [(rankValue (head card), last card)  card < cards]
count :: Eq a => a > [a] > Int
count x xs = length $ filter (== x) xs
evaluate :: [(Int, Char)] > [Int]
evaluate hand  straight && flush = 9 : ranks
 k 4 = 8 : kind 4 ++ kind 1
 k 3 && k 2 = 7 : kind 3 ++ kind 2
 flush = 6 : ranks
 straight = 5 : ranks
 k 3 = 4 : kind 3 ++ ranks
 k 2 && k' 2 [head (kind 2)] = 3 : kind 2 ++ kind' 2 [head (kind 2)] ++ ranks
 k 2 = 2 : kind 2 ++ ranks
 otherwise = 1 : ranks
where (r, suits) = unzip hand
ranks = sortBy (flip compare) r
flush = length (nub suits) == 1
straight = (maximum ranks)  (minimum ranks) == 4 && length (nub ranks) == 5
kind' n except = [rank  rank < ranks, count rank ranks == n, rank `notElem` except]
kind n = kind' n []
k' n except = not $ null $ kind' n except
k n = k' n []
main :: IO ()
main = do
str < readFile "/home/zach/code/euler/054/poker.txt"
let games = parse str
print $ length [left  (left, right) < games, evaluate left > evaluate right]
$ ghc O2 o poker poker.hs
$ time ./poker
real 0m0.012s
user 0m0.012s
sys 0m0.000s
Python
#!/usr/bin/env python
import os
from itertools import *
from operator import itemgetter
SCORE_FUNCS = []
def score_func(func):
SCORE_FUNCS.append(func)
return func
@score_func
def highest_card(cards):
return max(value for value, suit in cards)
@score_func
def one_pair(cards):
pairs = groups(cards, 2)
if len(pairs) == 1:
return 1e2 + 2e1 * max(pairs)
return 0
@score_func
def two_pair(cards):
pairs = groups(cards, 2)
if len(pairs) == 2:
return 1e3 + 2e2 * max(pairs)
return 0
@score_func
def three_of_a_kind(cards):
threes = groups(cards, 3)
if len(threes) == 1:
return 1e4 + 2e3 * max(threes)
return 0
@score_func
def straight(cards):
return 1e5 * int(all(b  a == 1 for a, b in pairwise(cards)))
@score_func
def flush(cards):
return 1e6 * int(len(suits(cards)) == 1)
@score_func
def full_house(cards):
return 1e7 * int(len(groups(cards, 2)) == 1 and len(groups(cards, 3)) == 1)
@score_func
def four_of_a_kind(cards):
fours = groups(cards, 4)
if len(fours) == 1:
return 1e8 + 2e7 * max(fours)
return 0
@score_func
def straight_flush(cards):
return 1e9 * int(len(suits(cards)) == 1 and all(b  a == 1 for a, b in pairwise(cards)))
@score_func
def royal_flush(cards):
return 1e10 * int(len(suits(cards)) == 1 and [value for value, suit in cards] == [10, 11, 12, 13, 14])
def score(cards):
return sum(score_func(cards) for score_func in SCORE_FUNCS)
def groups(cards, length):
return [k for k, g in groupby(value for value, suit in cards) if len(list(g)) == length]
def pairwise(cards):
a, b = tee(value for value, suit in cards)
next(b, None)
return zip(a, b)
def suits(cards):
return list({suit for value, suit in cards})
def cards(hand):
faces = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
return sorted(((int(faces.get(card[0], card[0])), card[1]) for card in hand), key=itemgetter(0))
def parse_hands(lines):
return ((cards(line.split()[:5]), cards(line.split()[5:])) for line in lines)
def winner(hands):
return int(score(hands[0]) < score(hands[1])) + 1
def main():
with open(os.path.join(os.path.dirname(__file__), 'poker.txt')) as f:
print(sum(1 for hands in parse_hands(f) if winner(hands) == 1))
if __name__ == "__main__":
main()
$ time python3 poker.py
real 0m0.113s
user 0m0.104s
sys 0m0.008s
Questions? Comments? Send me an email: [email protected]