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:

``````File.ReadAllText("day1.txt")
.Sum(c => c == '(' ? 1 : -1)
``````

C# part b:

``````File.ReadAllText("day1.txt")
.Scan(0, (f, d) => d == '(' ? f + 1 : f - 1)
.Select((floor, index) => new { floor, index })
.First(f => f.floor == -1)
.index
``````

F# part a:

``````File.ReadAllText("day1.txt")
|> Seq.sumBy (fun c -> if c = '(' then 1 else -1)
``````

F# part b:

``````File.ReadAllText("day1.txt")
|> 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.