0%

Problem 54


Problem 54


Poker hands

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 2C 3S 8S 8D TD Player 2
  Pair of Fives Pair of Eights  
2 5D 8C 9S JS AC 2C 5C 7D 8S QH Player 1
  Highest card Ace Highest card Queen  
3 2D 9C AS AH AC 3D 6D 7D TD QD Player 2
  Three Aces Flush with Diamonds  
4 4D 6S 9H QH QC 3D 6D 7H QD QS Player 1
  Pair of Queens Pair of Queens  
  Highest card Nine Highest card Seven  
5 2H 2D 4C 4D 4S 3C 3D 3S 9S 9D Player 1
  Full House Full House  
  with Three Fours with Three Threes  

The file, poker.txt, contains one-thousand 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?


扑克手牌

在扑克游戏中,玩家的手牌由五张牌组成,其等级由低到高分别为:

  • 单牌:牌面最大的一张牌。
  • 对子:两张牌面一样的牌。
  • 两对:两个不同的对子。
  • 三条:三张牌面一样的牌。
  • 顺子:五张牌的牌面是连续的。
  • 同花:五张牌是同一花色。
  • 葫芦:三条带一个对子。
  • 四条:四张牌面一样的牌。
  • 同花顺:五张牌的牌面是连续的且为同一花色。
  • 皇家同花顺:同一花色的10、J、Q、K、A。

牌面由小到大的顺序是:2、3、4、5、6、7、8、9、10、J、Q、K、A。

如果两名玩家的手牌处于同一等级,那么组成该等级的牌中牌面较大的一方获胜;例如,一对8胜过一对5(参见例1);如果这些牌的牌面相同,例如双方各有一对Q,那么就比较玩家手牌中牌面最大的牌(参见例4);如果最大的牌相同,则比较次大的牌,依此类推。

考虑以下五局游戏中双方的手牌:

手牌 玩家1 玩家2 胜者
1 红桃5 草花5 黑桃6 黑桃7 方片K 草花2 黑桃3 黑桃8 方片8 方片10 玩家2
  一对5 一对8  
2 方片5 草花8 黑桃9 黑桃J 草花A 草花2 草花5 方片7 黑桃8 红桃Q 玩家1
  单牌A 单牌Q  
3 方片2 草花9 黑桃A 红桃A 草花A 方片3 方片6 方片7 方片10 方片Q 玩家2
  三条A 同花方片  
4 方片4 黑桃6 红桃9 红桃Q 草花Q 方片3 方片6 红桃7 方片Q 黑桃Q 玩家1
  一对Q 一对Q  
  最大单牌9 最大单牌7  
5 红桃2 方片2 草花4 方片4 黑桃4 草花3 方片3 黑桃3 黑桃9 方片9 玩家1
  葫芦 葫芦  
  (三条4) (三条3)  

在文本文件poker.txt中,包含有两名玩家进行一千局扑克游戏的手牌。每一行包含有10张牌(均用一个空格隔开):前5张牌属于玩家1,后5张牌属于玩家2。你可以假定所有的手牌都是有效的(没有无效的字符或是重复的牌),每个玩家的手牌不一定按顺序排列,且每一局都有确定的赢家。

其中有多少局玩家1获胜?