Project Euler - Poker Hands (2) - F#

In previous post I showed a C# solution to the Poker-hands problem. Since I’ve become more and more interested in functional programming languages, I would like to create another solution in F# and give a comparison to the C# one.

##Solution

open System
open System.IO

type Player = | Player1 | Player2

let cards = ['0';'1';'2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; 'T'; 'J'; 'Q'; 'K'; 'A']
let royal = cards |> List.skip 10 |> Array.ofList
let cardOrder c = cards |> List.findIndex ((=) c)
let highToLow = cardOrder >> (-) 15

let isInfix (hand: char array) =
  let cardss = cards |> Array.ofList |> String

  hand
  |> String
  |> fun s -> cardss.Contains(s)
  |> (&&) (hand.Length = 5)

let handValue str =
  let freq      = Array.groupBy fst >> Array.map (fun (n, v) -> (n, v.Length)) >> Array.sortBy (fun (c, l) -> 100 * (5-l) + highToLow c)
  let hand      = str    |> Array.map (fun (s:string) -> (s.[0], s.[1]))
  let values    = hand   |> Array.map fst |> Array.sortBy cardOrder
  let valuesH2L = values |> Array.rev |> String
  let suits     = hand   |> Array.map snd

  let isFlush    = suits  |> Array.distinct |> Array.length |> (=) 1 // same suit
  let isStraight = values |> isInfix // consecutive
  let isRoyal    = values = royal

  let expFreq e a = a |> Array.map snd |> function | v when v = e -> a |> Array.map fst |> String |> Some | _ -> None

  let (|FourOfAKind|_|)  = expFreq [|4;1|]
  let (|ThreeOfAKind|_|) = expFreq [|3;1;1|]
  let (|FullHouse|_|)    = expFreq [|3;2|]
  let (|TwoPairs|_|)     = expFreq [|2;2;1|]
  let (|OnePair|_|)      = expFreq [|2;1;1;1|]

  match freq hand with
  | _ when isFlush && isRoyal     -> "900000"
  | _ when isFlush && isStraight  -> "8" + valuesH2L
  | FourOfAKind s                 -> "7000" + s
  | FullHouse   s                 -> "6000" + s
  | _ when isFlush                -> "5" + valuesH2L
  | _ when isStraight             -> "4" + valuesH2L
  | ThreeOfAKind s                -> "300" + s
  | TwoPairs s                    -> "200" + s
  | OnePair s                     -> "10" + s
  | _ -> "0" + valuesH2L


let playHand line =
  let h1 = line |> Array.take 5 |> handValue |> List.ofSeq
  let h2 = line |> Array.skip 5 |> handValue |> List.ofSeq

  let rec winner = function
  | ((a, b)::xs) when cardOrder a > cardOrder b -> Player1
  | ((a, b)::xs) when cardOrder a = cardOrder b -> winner xs
  | _ -> Player2

  List.zip h1 h2 |> winner

File.ReadAllLines(@"p054_poker.txt")
|> Seq.map (fun s -> s.Split ' ' |> playHand)
|> Seq.filter ((=) Player1)
|> Seq.length
|> printf "Player 1 won %d"

##Comparison

This implemetaion has only 66 lines of code which is much lesser than its C# conterpart. In C# soultion, I defined an interface, an abstract base class to abstract and encapsulate game rules. The business logic is hidding in each sub-class with the overhead of inheritance.

 ....
 public class Full_House: Rank {
    public Full_House(IEnumerable<string> cards) : base(cards) {

    }
    protected override bool Match() {

        return cards.GroupBy(c => Mapper[c[0]], c=> 1).Count(g => g.Count()==3) == 1 
            && cards.GroupBy(c => Mapper[c[0]], c=> 1).Count(g => g.Count()==2) == 1;
    }

   protected override double Remainder { 
       get{
         return GetGroups(3).First().Key * 15 + GetGroups(2).First().Key;
       }
   }
}   
...

In contrast, F#’s Discriminated unions enables a concise coding style when working with hierarchical data. Buisness logic is a collection of partially applied functions. This enables data to be processed streamly and results in an expressive and succinct code.

match freq hand with
| _ when isFlush && isRoyal     -> "900000"
| _ when isFlush && isStraight  -> "8" + valuesH2L
| FourOfAKind s                 -> "7000" + s
| FullHouse   s                 -> "6000" + s
| _ when isFlush                -> "5" + valuesH2L
| _ when isStraight             -> "4" + valuesH2L
| ThreeOfAKind s                -> "300" + s
| TwoPairs s                    -> "200" + s
| OnePair s                     -> "10" + s
| _ -> "0" + valuesH2L

Build a Backend With Node.js, Container and Azure (3)

In the last post, We have created an API that accepts registration request, saves user information into the database. Once a registration is completed, we want to send a welcome email to the user. Sending email is a time-consuming task, it should be done asynchronously outside the user request/response cycle. This enables web requests to return immediately, results in better response time and higher throughput.

Email worker

In this post we are going to create an email worker that runs in a separate process, pulls tasks from the message queue and sends emails.

var config = require('./config/config')
var nodemailer = require('nodemailer');

var EmailService = require('./src/email_service')

function handleError()  {
    this.close();
    setTimeout( function() {
        processor = start_worker();
    }
    , 10000)
}

function onMessage(data) {
    var email_address = data;
    var transporter = nodemailer.createTransport( {
        service: config.email.service ,
        auth: {
            user: config.email.user, // Your email id
            pass: config.email.pass  // Your password
        }
    });

    var mailOptions = {
        from: config.email.from, 
        to: email_address, 
        subject: 'Welcome!', 
        html: '<b>Thanks for registering</b>' 
    };

    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
        };
    });
}

function start_worker() {
    var emailProcessor = new EmailService();
    emailProcessor.once('error', handleError.bind(emailProcessor))
    emailProcessor.once('connect', (function() {
            this.process('email', onMessage)
        })
        .bind(emailProcessor) 
    )

    return emailProcessor.start();
}


var processor = start_worker();

We also need to install the nodemailer package which does the real work of email sending.

npm install --save nodemailer

Note that we are using the same repository as api. The EmailService is used by both api and work for message publish/subscribe.

In next post, we will put everything together. Start a dev database, message queue, launch the API server, run the task work.

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