Advent of Code Day 2 Solved in C# and F#
December 7. 2015 Posted in:
Here’s my solutions to day 2 of the Advent of Code challenge, once again using LINQ in C# and then solving in F#:
If you want to see the code. Here’s part a in C#
File.ReadAllLines("day2.txt")
.Select(s => s.Split('x'))
.Select(x => x.Select(Int32.Parse))
.Select(w => w.OrderBy(x => x).ToArray())
.Select(w => 3 * w[0] * w[1] + 2 * w[0] * w[2] + 2 * w[1] * w[2])
.Sum()
Part b in C#
File.ReadAllLines("day2.txt")
.Select(s => s.Split('x'))
.Select(x => x.Select(Int32.Parse))
.Select(w => w.OrderBy(x => x).ToArray())
.Select(w => 2 * w[0] + 2 * w[1] + w[0] * w[1] * w[2])
.Sum()
Part a in F#
File.ReadAllLines("day2.txt")
|> Seq.map (fun s -> s.Split('x') |> Seq.map int |> Seq.sort |> Seq.toArray)
|> Seq.map (fun w -> 3 * w.[0] * w.[1] + 2 * w.[0] * w.[2] + 2 * w.[1] * w.[2])
|> Seq.sum
Part b in F#
File.ReadAllLines("day2.txt")
|> Seq.map(fun s->s.Split('x') |> Seq.map int |> Seq.sort |> Seq.toArray)
|> Seq.map(fun w-> 2 * w.[0] + 2 * w.[1] + w.[0] * w.[1] * w.[2])
|> Seq.sum
Want to learn more about LINQ? Be sure to check out my Pluralsight course LINQ Best Practices.
Comments
That's nice ; it can be shortened a little though
Alternatively here is what I've done (note: for each challenge I tried to separate some common code for both parts and just parametrize what is required for each)
Sehnsucht
nice, yes I should have thought of sumBy, and I'm using a pattern matching a lot more these days but still missing plenty of places I could use it
Mark Heath