Add Day 3
This commit is contained in:
65
Day3/Program.cs
Normal file
65
Day3/Program.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
var memory = File.ReadAllText("input.txt");
|
||||
|
||||
var result = ParseCorruptedMemory(memory);
|
||||
var resultPart2 = ParseCorruptedMemoryPart2(memory);
|
||||
Console.WriteLine($"Part1: {result}\nPart2: {resultPart2}");
|
||||
|
||||
int ParseCorruptedMemory(string corruptedMemory)
|
||||
{
|
||||
var mulPattern = @"mul\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)";
|
||||
var matches = Regex.Matches(corruptedMemory, mulPattern);
|
||||
|
||||
var totalSum = matches
|
||||
.Select(match =>
|
||||
{
|
||||
var x = int.Parse(match.Groups[1].Value);
|
||||
var y = int.Parse(match.Groups[2].Value);
|
||||
|
||||
return x * y;
|
||||
}).Sum();
|
||||
|
||||
return totalSum;
|
||||
}
|
||||
|
||||
int ParseCorruptedMemoryPart2(string corruptedMemory)
|
||||
{
|
||||
var mulPattern = @"mul\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)";
|
||||
var doPattern = @"do\s*\(\s*\)";
|
||||
var dontPattern = @"don't\s*\(\s*\)";
|
||||
|
||||
var mulEnabled = true;
|
||||
var mulMatches = Regex.Matches(corruptedMemory, mulPattern);
|
||||
var doMatches = Regex.Matches(corruptedMemory, doPattern);
|
||||
var dontMatches = Regex.Matches(corruptedMemory, dontPattern);
|
||||
|
||||
var allMatches = mulMatches
|
||||
.Concat(doMatches.Cast<Match>())
|
||||
.Concat(dontMatches.Cast<Match>())
|
||||
.OrderBy(m => m.Index)
|
||||
.ToList();
|
||||
|
||||
var results = new List<int>();
|
||||
|
||||
foreach (var match in allMatches)
|
||||
{
|
||||
if (Regex.IsMatch(match.Value, doPattern))
|
||||
{
|
||||
mulEnabled = true;
|
||||
}
|
||||
else if (Regex.IsMatch(match.Value, dontPattern))
|
||||
{
|
||||
mulEnabled = false;
|
||||
}
|
||||
else if (Regex.IsMatch(match.Value, mulPattern) && mulEnabled)
|
||||
{
|
||||
var mulMatch = (Match)match;
|
||||
var x = int.Parse(mulMatch.Groups[1].Value);
|
||||
var y = int.Parse(mulMatch.Groups[2].Value);
|
||||
results.Add(x * y);
|
||||
}
|
||||
}
|
||||
|
||||
return results.Sum();
|
||||
}
|
||||
Reference in New Issue
Block a user