0 Comments Posted in:

Last week I mentioned the Advent of Code challenge, a series of fun programming challenges, one for each day of the month. I’ve been doing these challenges myself, and I’ve decided to post videos describing my solutions.

Each puzzle I solve in two ways, first using LINQ and C#, in a single expression if possible. Then I try to convert it to F#, which is mainly to improve my fluency with F# and hopefully to pick up some new tricks along the way.

I’m trying to keep the videos under 10 minutes each, although some have sneaked over. They’re rough and ready, with minimal editing, but I hope you can learn something helpful from them anyway.

Here’s day one’s solution:

Here’s the solutions in C# and F#, with the input factored out into a text file:

C# part a:

    .Sum(c => c == '(' ? 1 : -1)

C# part b:

    .Scan(0, (f, d) => d == '(' ? f + 1 : f - 1)
    .Select((floor, index) => new { floor, index })
    .First(f => f.floor == -1)

F# part a:

    |> Seq.sumBy (fun c -> if c = '(' then 1 else -1)

F# part b:

    |> Seq.map (fun d -> if d = '(' then 1 else -1)
    |> Seq.scan (+) 0 
    |> Seq.findIndex (fun f -> f = -1)
Want to learn more about LINQ? Be sure to check out my Pluralsight course More Effective LINQ.
Vote on HN