Occa­sion­ally you might want to make the value of a sta­tic or instance field local to a thread (i.e. each thread holds an inde­pen­dent copy of the field), what you need in this case, is a thread-local stor­age.

In C#, there are mainly two ways to do this.

Thread­Sta­tic

You can mark a field with the Thread­Sta­tic attribute:

[ThreadStatic]
public static int _x;
…
Enumerable.Range(1, 10).Select(i => new Thread(() => Console.WriteLine(_x++))).ToList()
          .ForEach(t => t.Start()); // prints 0 ten times

Whilst this is the eas­i­est way to imple­ment thread-local stor­age in C# it’s impor­tant to under­stand the lim­i­ta­tions here:

  • the Thread­Sta­tic attribute doesn’t work with instance fields, it com­piles and runs but does nothing..
[ThreadStatic]
public int _x;
…
Enumerable.Range(1, 10).Select(i => new Thread(() => Console.WriteLine(_x++))).ToList()
          .ForEach(t => t.Start()); // prints 0, 1, 2, … 9
  • field always start with the default value
[ThreadStatic]
public static int _x = 1;
…
Enumerable.Range(1, 10).Select(i => new Thread(() => Console.WriteLine(_x++))).ToList()
          .ForEach(t => t.Start()); // prints 0 ten times

ThreadLocal<T>

C#  4 has intro­duced a new class specif­i­cally for the thread-local stor­age of data – the ThreadLocal<T> class:

private readonly ThreadLocal<int> _localX = new ThreadLocal<int>(() => 1);
…
Enumerable.Range(1, 10).Select(i => new Thread(() => Console.WriteLine(_localX++))).ToList()
          .ForEach(t => t.Start()); // prints 1 ten times

There are some bonuses to using the ThreadLocal<T> class:

  • val­ues are lazily eval­u­ated, the fac­tory func­tion eval­u­ates on the first call for each thread
  • you have more con­trol over the ini­tial­iza­tion of the field and is able to ini­tial­ize the field with a non-default value

Sum­mary

As you can see, using ThreadLocal<T> has some clear advan­tages over Thread­Sta­tic, though using 4.0 only fea­tures like ThreadLocal<T> means you have to tar­get your project at the .Net 4 frame­work and is there­fore not back­ward com­pat­i­ble with pre­vi­ous ver­sions of the framework.

It’s also worth not­ing that besides ThreadLocal<T> and Thread­Sta­tic you can also use Thread.GetData and Thread.SetData to fetch and store thread spe­cific data from and to a named Local­Data­S­toreS­lot though this is usu­ally cumbersome…

Share

Prob­lem

In the card game poker, a hand con­sists of five cards and are ranked, from low­est to high­est, in the fol­low­ing way:

  • High Card: High­est value card.
  • One Pair: Two cards of the same value.
  • Two Pairs: Two dif­fer­ent pairs.
  • Three of a Kind: Three cards of the same value.
  • Straight: All cards are con­sec­u­tive 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 con­sec­u­tive val­ues of same suit.
  • Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

The cards are val­ued in the order:

2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two play­ers have the same ranked hands then the rank made up of the high­est value wins; for exam­ple, a pair of eights beats a pair of fives (see exam­ple 1 below). But if two ranks tie, for exam­ple, both play­ers have a pair of queens, then high­est cards in each hand are com­pared (see exam­ple 4 below); if the high­est cards tie then the next high­est cards are com­pared, and so on.

Con­sider the fol­low­ing five hands dealt to two players:

image

The file, poker.txt, con­tains one-thousand ran­dom hands dealt to two play­ers. Each line of the file con­tains ten cards (sep­a­rated by a sin­gle 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 char­ac­ters or repeated cards), each player’s hand is in no spe­cific order, and in each hand there is a clear winner.

How many hands does Player 1 win?

Solu­tion

open System.IO

// define the suits
type Suit = | Heart | Club | Spade | Diamond

// define the card values
type CardValue =
    | ValueCard of int | Jack | Queen | King | Ace
    // define the + unary operator on the CardValue type
    static member (~+) (value:CardValue) =
        match value with
        | ValueCard n -> if n < 10 then ValueCard (n+1) else Jack
        | Jack -> Queen | Queen -> King | King -> Ace | Ace -> ValueCard(2)

// define the Card type
type Card = { Value:CardValue; Suit:Suit }

// define the ranks
type Rank =
    | HighCard of CardValue
    | OnePair of CardValue
    | TwoPairs of CardValue * CardValue
    | Three of CardValue
    | Straight of CardValue // highest value card
    | Flush
    | FullHouse of CardValue * CardValue
    | Four of CardValue
    | StraightFlush of CardValue // highest value card & suit
    | RoyalFlush

// define function to check if cards are the same suit
let isSameSuit (cards:Card list) = cards |> List.forall (fun c -> c.Suit = cards.Head.Suit)

// define function to get the highest card
let getHighestCard(cards:Card list) = cards |> List.maxBy (fun card -> card.Value)

// define function to check if cards are a straight set
let isStraight (cards:Card list) =
    let flag = cards |> List.sort |> Seq.windowed 2
    |> Seq.forall (fun [|card1; card2|] -> card2.Value = +card1.Value)

    (flag, getHighestCard cards)

// define function to get the duplicated cards
let getDupes (cards:Card list) =
    cards
    |> Seq.groupBy (fun card -> card.Value)
    |> Seq.map (fun (k, seq) -> (k, Seq.length seq))
    |> Seq.filter (fun (k, len) -> len > 1)
    |> Seq.toList

// evaluate the given hand of cards to return the rank
let evaluateHand (cards:Card list) =
    let (isStraight, highCard) = isStraight cards
    let sameSuit = isSameSuit cards
    
    if sameSuit && isStraight && highCard.Value = Ace then RoyalFlush
    else if sameSuit && isStraight then StraightFlush(highCard.Value)
    else if sameSuit then Flush
    else if isStraight then Straight(highCard.Value)
    else
        let dupes = getDupes cards
        if dupes.Length = 0 then HighCard(highCard.Value)
        else if dupes.Length = 1 then
            match dupes.[0] with
            | (cardValue,2) -> OnePair(cardValue)
            | (cardValue,3) -> Three(cardValue)
            | (cardValue,4) -> Four(cardValue)
        else
            match dupes with
            | [(cardValue',2);(cardValue'',2)] -> TwoPairs(cardValue', cardValue'')
            | [(cardValue',3);(cardValue'',2)] -> FullHouse(cardValue', cardValue'')
            | [(cardValue',2);(cardValue'',3)] -> FullHouse(cardValue'', cardValue')

// define function to check if player 1 wins
let isP1Winner (p1:Card list) (p2:Card list) =
    let p1Rank, p2Rank = evaluateHand p1, evaluateHand p2

    if p1Rank > p2Rank then true
    else if p1Rank = p2Rank then
        let rec compareHighCard (p1':Card list) (p2':Card list) =
            let p1'HighCard, p2'HighCard = getHighestCard p1', getHighestCard p2'
            if p1'HighCard.Value > p2'HighCard.Value then true
            else if p1'HighCard.Value = p2'HighCard.Value then
                let p1'' = p1' |> List.filter (fun c -> c.Value < p1'HighCard.Value)
                let p2'' = p2' |> List.filter (fun c -> c.Value < p2'HighCard.Value)
                compareHighCard p1'' p2''
            else false

        compareHighCard p1 p2
    else false

// define function to parse, say, "3D" into a 3 of Diamond
let parseCard [|(value:char);(suit:char)|] =
    let cardValue =
        match value with
        | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' -> ValueCard(int(value.ToString()))
        | 'T' -> ValueCard(10) | 'J' -> Jack | 'Q' -> Queen | 'K' -> King | 'A' -> Ace
    let suit =
        match suit with
        | 'S' -> Spade | 'H' -> Heart | 'D' -> Diamond | 'C' -> Club
    { Card.Value=cardValue; Suit=suit }

// get the array of all the dealt hands from the poker text file
let hands =
    File.ReadAllLines(@"C:\TEMP\poker.txt")
    |> Array.map (fun str -> 
        str.Split(' ') 
        |> Array.map (fun str -> parseCard (str.ToCharArray())))

// separate the hands into two different arrays, one for player 1 and the other player 2
let p1Hands = hands |> Array.map (fun cards -> cards |> Seq.take 5 |> Seq.toList)
let p2Hands = hands |> Array.map (fun cards -> cards |> Seq.skip 5 |> Seq.toList)

let answer =
    Array.map2 (fun p1 p2 -> isP1Winner p1 p2) p1Hands p2Hands
    |> Array.filter (fun b -> b)
    |> Array.length
Share

Prob­lem

The rules for writ­ing Roman numer­als allow for many ways of writ­ing each num­ber (see FAQ:Roman Numer­als). How­ever, there is always a “best” way of writ­ing a par­tic­u­lar number.

For exam­ple, the fol­low­ing rep­re­sent all of the legit­i­mate ways of writ­ing the num­ber sixteen:

IIIIIIIIIIIIIIII

VIIIIIIIIIII

VVIIIIII

XIIIIII

VVVI

XVI

The last exam­ple being con­sid­ered the most effi­cient, as it uses the least num­ber of numerals.

The 11K text file, roman.txt (right click and ‘Save Link/Target As…’), con­tains one thou­sand num­bers writ­ten in valid, but not nec­es­sar­ily min­i­mal, Roman numer­als; that is, they are arranged in descend­ing units and obey the sub­trac­tive pair rule (see FAQ for the defin­i­tive rules for this problem).

Find the num­ber of char­ac­ters saved by writ­ing each of these in their min­i­mal form.

Note: You can assume that all the Roman numer­als in the file con­tain no more than four con­sec­u­tive iden­ti­cal units.

Solu­tion

open System.IO

// define the set of available roman numerals
let romanNumerals = [(['I'],1I);(['I';'V'],4I);(['V'],5I);(['I';'X'],9I);
                     (['X'],10I);(['X';'L'],40I);(['L'],50I);(['X';'C'],90I);
                     (['C'],100I);(['C';'D'],400I);(['D'],500I);(['C';'M'],900I);
                     (['M'],1000I)]

// define function to get the numeric value of a roman numeral
let getNumericValue (numeral:char) =
    snd (romanNumerals |> Seq.filter (fun (l, v) -> l.Length = 1 && l.[0] = numeral) |> Seq.head)

// define function to convert a roman numerals to its corresponding numeric value
let toNumeric (numerals:string) =
    let rec toNumericRec ((head::tail):char list) (num:bigint) =
        match head, tail with
        | _, [] -> num + getNumericValue head
        | _, hd::tl when getNumericValue head >= getNumericValue hd ->
            toNumericRec tail (num + getNumericValue head)
        | _, hd::[] -> // subtractive pair as last number i.e. XIX - 19
            num + getNumericValue hd - getNumericValue head
        | _, hd::tl -> // subtractive pair not as last number XCV - 95
            toNumericRec tl (num + getNumericValue hd - getNumericValue head)

    toNumericRec (numerals.ToCharArray() |> Array.toList) 0I

// converts an integer value to corresponding minimal roman numerals form
let toMinimalRomanNumerals (value:bigint) =
    let rec toMinimalRomanNumeralsRec (value:bigint) (list:char list) =
        if value = 0I then list
        else
            let (list', value') =
                romanNumerals
                |> List.sortBy (fun (l, v) -> -v)
                |> Seq.filter (fun (l, v) -> v <= value)
                |> Seq.head
            toMinimalRomanNumeralsRec (value-value') (list@list')

    toMinimalRomanNumeralsRec value []

let original = File.ReadAllLines(@"C:\TEMP\roman.txt")
let minimal = original |> Array.map toNumeric |> Array.map toMinimalRomanNumerals

let answer =
    let originalLen = original |> Array.sumBy (fun str -> str.Length)
    let minimalLen = minimal |> Array.sumBy (fun str -> str.Length)
    originalLen - minimalLen
Share

Prob­lem

Con­sider qua­dratic Dio­phan­tine equa­tions of the form:

x2 – Dy2 = 1

For exam­ple, when D=13, the min­i­mal solu­tion in x is 6492 – 13x1802 = 1.

It can be assumed that there are no solu­tions in pos­i­tive inte­gers when D is square.

By find­ing min­i­mal solu­tions in x for D = {2, 3, 5, 6, 7}, we obtain the following:

32 – 2x22 = 1

22 – 3x12 = 1

92 – 5x42 = 1

52 – 6x22 = 1

82 – 7x32 = 1

Hence, by con­sid­er­ing min­i­mal solu­tions in x for D <= 7, the largest x is obtained when D=5.

Find the value of D <= 1000 in min­i­mal solu­tions of x for which the largest value of x is obtained.

Solu­tion

// define function to get the continued fractions, a0,a1,a2,...an
let continuedFraction D =
    // define functions for working out the nth term of P, Q and a sequence
    let getPn an' qn' pn' = an' * qn' - pn'
    let getQn D pn qn' = (D - pown pn 2) / qn'
    let getAn a0 pn qn = (a0 + pn) / qn

    // work out the initial terms
    let a0 = bigint(sqrt(double(D)))
    let p1, q1 = a0, D-a0*a0
    let a1 = getAn a0 p1 q1
    let initial = (p1, q1, a1)

    Seq.unfold (fun (pn', qn', an') ->
        let pn = getPn an' qn' pn'
        let qn = getQn D pn qn'
        let an = getAn a0 pn qn
        Some((pn', qn', an'), (pn, qn, an))) initial
    |> Seq.map (fun (pn, qn, an) -> an)
    |> Seq.append [a0]

// define function to get the continued fraction convergents
// e.g. for D = 7: 2/1, 3/1, 5/2, 8/3, ...
let continuedFractionConvergents D =
    let getN an n' n'' = an * n' + n''

    // work out the initial terms
    let fractions = continuedFraction D
    let a0 = Seq.head fractions
    let p0, p1 = a0, a0 * (Seq.nth 1 fractions) + 1I
    let q0, q1 = 1I, Seq.nth 1 fractions
    let initial = (p1, q1, p0, q0)

    Seq.scan (fun (pn', qn', pn'', qn'') an ->
        let pn = getN an pn' pn''
        let qn = getN an qn' qn''
        (pn, qn, pn', qn')) initial (fractions |> Seq.skip 2)
    |> Seq.map (fun (pn, qn, pn', qn') -> (pn, qn))
    |> Seq.append [(p0, q0)]

let answer =
    [1I..1000I]
    |> List.filter (fun d -> sqrt(double(d)) % 1.0 <> 0.0)
    |> List.maxBy (fun d ->
        continuedFractionConvergents d
        |> Seq.filter (fun (x, y) -> x*x - d*y*y = 1I)
        |> Seq.map fst
        |> Seq.head)

After spend­ing much time read­ing the infor­ma­tion on Pell’s equa­tion on math­world and wikipedia, it turns out that the best way to solve the equa­tion for a given D is to work out the con­tin­ued frac­tion con­ver­gents to the square root of D.

For exam­ple, for D = 7, the equa­tion becomes:

image

The fun­da­men­tal solu­tion (the first pair of x, y which sat­is­fies the equa­tion) can be obtained by going through the sequence of con­ver­gents for the square root of 7:

image image
image image
image image
image image
image image

So how do we work­out the val­ues of the con­ver­gents? The con­tin­ued frac­tion for a num­ber is usu­ally writ­ten as

image

The first ten val­ues gen­er­ated by the con­tin­ued frac­tion for the square root of 2 are:

1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, …

These val­ues are called con­tin­ued frac­tion con­ver­gents, get­ting closer to the true value of square root 2 with each step..

So, to find the con­ver­gents to the square root of D, we first need to find the val­ues of a:

clip_image002[8]

clip_image004

clip_image002[10]

clip_image002[6]

Once we have the sequence of val­ues for a, we can then find out the con­ver­gent values:

clip_image002[12]

clip_image004[6]

The rest is sim­ple, for each value of D between 1 and 1000, go through the con­ver­gents to find the fun­da­men­tal solu­tion and return the max value of x in all the fun­da­men­tal solutions.

Share

Oh, the Pain!

Now and again we all come across an object which requires ini­tial­iza­tion before it can be used but with noth­ing there to stop us from try­ing to use it before it’s initialized.

In most cases you will get a seem­ingly unre­lated excep­tion (e.g. null ref­er­ence when the object tries to use some resource which it expects to be set dur­ing ini­tial­iza­tion), which aren’t very help­ful at all when you try to debug/identify the problem.

If you’re lucky, the object you’re using might have been designed with this in mind and gives you a mean­ing­ful excep­tion when you try to call a method which requires the object to be ini­tial­ized first, in which case it should be a straight­for­ward to fix your code accord­ingly. For the guys design­ing the class though, this usu­ally means they have to lit­ter their code with val­i­da­tion logic and often means dupli­cated val­i­da­tion code or unnec­es­sary inher­i­tance just to encap­su­late the val­i­da­tion logic.

For­tu­nately, with the help of Post­Sharp, a sim­ple attribute can take care of this chore for you with ease!

Define high level interface

First off, you need a nice and sim­ple inter­face like this:

/// <summary>
/// Marks a component which needs to be initialized before it can be used
/// </summary>
public interface IInitializable<T>
{
    bool IsInitialized { get; }

    void Initialize(T initObject);
}

Ini­tial­iza­tion­Re­quire­dAt­tribute

The attribute will look some­thing like this (in Post­Sharp 2):

[Serializable]
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class InitializationRequiredAttribute : MethodInterceptionAspect
{
    public override bool CompileTimeValidate(MethodBase method)
    {
        // make sure that the attribute is used in a type that implements the 
        // IInitializable interface
        if (!method.DeclaringType.GetInterfaces()
                   .Any(i => i.IsGenericType &&
                             i.GetGenericTypeDefinition() == typeof(IInitializable<>)))
        {
            throw new Exception(string.Format(
                "The [{0}] attribute can only be used in types that implement the [{1}] interface",
                GetType(), typeof(IInitializable<>)));
        }
        return base.CompileTimeValidate(method);
    }

    /// <summary>
    /// Checks the IsInitialized property before allowing the call to proceed
    /// </summary>
    public override void OnInvoke(MethodInterceptionArgs eventArgs)
    {
        var propertyInfo = eventArgs.Instance.GetType().GetProperty("IsInitialized");
        if (propertyInfo != null)
        {
            var propertyValue = propertyInfo.GetValue(eventArgs.Instance, null);
            if (propertyValue != null && propertyValue is bool && (bool) propertyValue)
            {
                // only proceed with the call if the instance has been initialized
                eventArgs.Proceed();
                return;
            }
        }
        throw new InstanceNotInitializedException(eventArgs.Method.Name);
    }
}

I have enforced a rule that this attribute can only be used in a class which imple­ments our IIni­tial­iz­able inter­face, you can relax this rule by remov­ing the over­rid­den Com­pile­TimeVal­i­date method. How­ever, in my expe­ri­ence it’s best to not leave any grey area in your code just in case you run into a sit­u­a­tion where you had expected the attribute to do its job only to find out later that something’s gone wrong because you had accidentally/purposely removed the IIni­tial­iz­able inter­face from your class.

Usage

To use the attribute:

public class MyClass : IInitializable<string>
{
    public bool IsInitialized { get; private set; }
    public void Initialize(string initializationData)
    {
        …
        IsInitialized = true;
    }

    [InitializationRequired]
    public void DoSomething() { }
}
Share