Advent of Code Day 1 Solution in C# and F#
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)
Comments
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) :)
Then that can be combined directly in the scan (if wanted)
findIndex line can also be shortened in the same vein you did for scan.
Sehnsucht
thanks for the tips. I was hoping you'd do some code reviews for me :)
Mark HeathAnd I understand about the video format. I'll try to put my answers as github gists when I post about the next ones.