63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
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)
|
|
.Concat(dontMatches)
|
|
.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 x = int.Parse(match.Groups[1].Value);
|
|
var y = int.Parse(match.Groups[2].Value);
|
|
results.Add(x * y);
|
|
}
|
|
}
|
|
|
|
return results.Sum();
|
|
} |