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:

    |> (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 LINQ Best Practices.


Comment by Sehnsucht

Not a fan of the video format ; I prefer when I can copy/paste easily the code to test (not a big deal though)
Pattern matching can also be used (some people say that it can be more efficient than using if) :) (function '(' -> 1 | _ -> -1)

Then that can be combined directly in the scan (if wanted)

|> Seq.scan (fun acc -> function '(' -> acc + 1 | _ -> acc - 1) 0

findIndex line can also be shortened in the same vein you did for scan.

Seq.findIndex ((=) -1) // or ((>) 0)

Comment by Mark Heath

thanks for the tips. I was hoping you'd do some code reviews for me :)
And I understand about the video format. I'll try to put my answers as github gists when I post about the next ones.

Mark Heath