Project Euler - Poker Hands (1) - C# Solution

To see the real power of a functional langulage, I would apply it to a complicate problem. The problem 54, porker hands looks a good candidate for this advanture.

##Problem

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
2 5D 8C 9S JS AC 2C 5C 7D 8S QH Player 1
3 2D 9C AS AH AC 3D 6D 7D TD QD Player 2
4 4D 6S 9H QH QC 3D 6D 7H QD QS Player 1
5 2H 2D 4C 4D 4S 3C 3D 3S 9S 9D Player 1

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?

C# solution

Obviously, the core of this solution is to rank each hand of cards. We are going to model it as the following.

public interface IRank
{
    Tuple<int, double> Score(int order);
} 

public abstract class Rank : IRank {

    public static readonly IDictionary<char, int>  Mapper = new Dictionary<char, int> {
         {'1',1}, {'2',2}, {'3',3}, {'4',4}, {'5',5}, {'6',6}, {'7',7}, {'8',8}, {'9',9}, {'T',10}, {'J',11}, {'Q',12}, {'K',13}, {'A',14}
    };

    protected readonly IEnumerable<string> cards = null;

    public Rank(IEnumerable<string> cards) {
         this.cards = cards;
    }

    public virtual Tuple<int, double> Score(int order) {
        if (Match() == false) {
            return new Tuple<int,double>(0,0);
        }

        return new Tuple<int,double>(order, Remainder);
    }

    protected abstract bool Match();

    protected virtual double Remainder {
        get {
            return 0;
        }
    } 

    protected IEnumerable<IGrouping<int, int>> GetGroups(int level) {
        return cards.GroupBy(c => Mapper[c[0]], c=> 1).Where(g => g.Count() == level).OrderBy(c => c.Key);
    }
}

We use Rank class to abstract the game rules. Each child class encapsulates a certain cards pattern and its corresponding weight. When the game starts, all rank instances are evaluated. If the current hand matches a rank’s pattern, a score will be returned. The first item will be the rank’s order(significance), and the second item is a caculated number used to compare hands with the same rank. Otherwise, a Tuple<0,0> will be returned.

public class Game {

    // return 1 if player wins, otherwise return 0;
    public static int Judge(string hands) {
        var cards = hands.Split(' ');
        var _player1 = new Hand(cards.Take(5));
        var _player2 = new Hand(cards.Skip(5).Take(5));

        if (_player1.Weight.Item1 ==  _player2.Weight.Item1) {
            return _player1.Weight.Item2 >  _player2.Weight.Item2 ? 1 : 0;
        }

        return _player1.Weight.Item1 > _player2.Weight.Item1 ? 1 : 0;
    }
}


public class Hand {

    readonly IEnumerable<IRank> _ranks = null;
    readonly IEnumerable<string> _cards = null;

    public Hand(IEnumerable<string> cards) {
        if ( cards?.Count() != 5 ) {
            throw new Exception();
        }
        _cards = cards;

        _ranks = new List<IRank> {
            new High_Card(cards),
            new One_Pair(cards),
            new Two_Pairs(cards),
            new Three_Of_Kinds(cards),
            new Straight(cards),
            new Flush(cards),
            new Full_House(cards),
            new Four_Of_Kinds(cards),
            new Straight_Flush(cards),
            new Royal_Flush(cards)
        };
    }

    public Tuple<int,double> Weight {
        get {
            return  _ranks.Select((r, order) => r.Score(order))
            .Where(r => r.Item2 > 0)
            .OrderBy(r => r.Item1)
            .Last();
        }
    }

I really enjoy having unit tests to guild my implementation at small steps towards a final solution. My brain is just not powerful enough to keep all the rules, edge cases in mind. Writing tests leads to better desgined, easy to maintained code. public class Hand_tests {

[Fact]
public void Hight_card()
{
    var result = Game.Judge("8C TS KC 9H 4S 7D 2S 5D 3S AC");
    Assert.True(result == 0);
}

[Fact]
public void One_pair_vs_hight_card()
{
    var result = Game.Judge("5H 8C 6S 2S 2D AC KS QS TD 9D");
    Assert.True(result == 1);
}

[Fact]
public void Two_Pairs_pair_over_one_pair()
{
    var result = Game.Judge("2C 2S 3S 3D 4D AH AC KS QS JD");
    Assert.True(result == 1);
}

[Fact]
public void Three_of_kind_vs_two_pairs()
{
    var result = Game.Judge("2S 2D 2K 3D 4D AD AC KS KH QC");
    Assert.True(result == 1);
}

[Fact]
public void Straight_vs_three_of_kind()
{
    var result = Game.Judge("2C 3D 4D 5H 6D AD AC AS KH QC");
    Assert.True(result == 1);
}

[Fact]
public void flash_vs_straight()
{
    var result = Game.Judge("2D 4D 5D 7D 8D AD AC AS KH QC");
    Assert.True(result == 1);
}

[Fact]
public void Full_house_vs_flash()
{
    var result = Game.Judge("2D 2S 2H 3D 3C AD 9D KD 7D 6D");
    Assert.True(result == 1);
}

...

Once all the test scenarios are passed, we can be confident to get correct result

public class Program
{
    public static void Main(string[] args)
    {
        using(var reader = File.OpenText("p054_poker.txt")) {
            var line = reader.ReadLine();
            var player1_wins = 0;

            while(line !=null) {
                player1_wins += Game.Judge(line);
                line = reader.ReadLine();
            }

            Console.WriteLine("Player 1 wins");
            Console.WriteLine(player1_wins);
        }
    }
}

Source Code

Conclusion

We see some of the benifits of OOP here. A clear modular structure good for defining abstract types where implementation details are hidden and the unit has a clearly defined interface. Implementation can be shared between classes.

However, for algorithm focused problems, function languages normally produce a more concise, efficient solution. In post, I will revisit this problem with a functional solution