Files

63 lines
1.8 KiB
C#
Raw Permalink Normal View History

2024-12-03 08:44:25 +02:00
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
2024-12-03 08:47:08 +02:00
.Concat(doMatches)
.Concat(dontMatches)
2024-12-03 08:44:25 +02:00
.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)
{
2024-12-03 08:47:08 +02:00
var x = int.Parse(match.Groups[1].Value);
var y = int.Parse(match.Groups[2].Value);
2024-12-03 08:44:25 +02:00
results.Add(x * y);
}
}
return results.Sum();
}