I didn't do day 7. I'll add my solution if I do. Anyway, here's day 8:
Day 8:
Part 1:
Code:
Part 2:
Code:
Both of these could be slightly reduced by doing the math in the Select--thus selecting an integer--and then having an empty Sum--which knows how to sum integers by default--but this made debugging easier.
Also note that I've made the SplitOnNewLine() extension method because I was tired of typing it out each time. It's just this:
Code:
EDIT:
Oh, I realized I don't need the select at all, and can just do it with a sum. So here're the reduced answers:
Part 1:
Code:
Part 2:
Code:
Day 8:
Part 1:
Code:
input.SplitOnNewLine().Select(s => new { CodeLength = s.Length, MemLength = s.Substring(1, s.Length-2).Aggregate(new { Count = 0, EscapeCount = 0 }, (agg, current) => agg.EscapeCount == -1 ? new { Count = agg.Count, EscapeCount = current == '"' || current == '\\' ? 0 : 2 } : agg.EscapeCount > 0 ? new { Count = agg.Count, EscapeCount = agg.EscapeCount - 1 } : current == '\\' ? new { Count = agg.Count + 1, EscapeCount = -1 } : new { Count = agg.Count + 1, EscapeCount = 0 }, a => a.Count) }).Sum(a => a.CodeLength - a.MemLength)
Part 2:
Code:
input.SplitOnNewLine().Select(s => new { CodeLength = s.Length, EncodedLength = s.Sum(c => c == '"' || c == '\\' ? 2 : 1) + 2 }).Sum(a => a.EncodedLength - a.CodeLength)
Both of these could be slightly reduced by doing the math in the Select--thus selecting an integer--and then having an empty Sum--which knows how to sum integers by default--but this made debugging easier.
Also note that I've made the SplitOnNewLine() extension method because I was tired of typing it out each time. It's just this:
Code:
static string[] SplitOnNewLine(this string s) => s.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
EDIT:
Oh, I realized I don't need the select at all, and can just do it with a sum. So here're the reduced answers:
Part 1:
Code:
input.SplitOnNewLine().Sum(s => s.Length - s.Substring(1, s.Length-2).Aggregate(new { Count = 0, EscapeCount = 0 }, (agg, current) => agg.EscapeCount == -1 ? new { Count = agg.Count, EscapeCount = current == '"' || current == '\\' ? 0 : 2 } : agg.EscapeCount > 0 ? new { Count = agg.Count, EscapeCount = agg.EscapeCount - 1 } : current == '\\' ? new { Count = agg.Count + 1, EscapeCount = -1 } : new { Count = agg.Count + 1, EscapeCount = 0 }, a => a.Count))
Part 2:
Code:
input.SplitOnNewLine().Sum(s => s.Sum(c => c == '"' || c == '\\' ? 2 : 1) + 2 - s.Length)