feat: solved day 3

This commit is contained in:
Stevan Freeborn
2024-12-03 23:50:01 -06:00
parent 0a7b6b2291
commit d658c31ffe
9 changed files with 225 additions and 15 deletions
+12
View File
@@ -0,0 +1,12 @@
namespace MullItOver;
public abstract class Instruction {};
class MulInstruction(int multiplicandOne, int multiplicandTwo) : Instruction
{
public int Execute() => multiplicandOne * multiplicandTwo;
}
class DontInstruction : Instruction;
class DoInstruction : Instruction;
+28
View File
@@ -0,0 +1,28 @@
namespace MullItOver;
public static class InstructionExtensions
{
public static int Execute(this List<Instruction> instructions)
{
var isEnabled = true;
var sum = 0;
foreach (var instruction in instructions)
{
switch (instruction)
{
case DontInstruction:
isEnabled = false;
continue;
case DoInstruction:
isEnabled = true;
continue;
case MulInstruction mul when isEnabled:
sum += mul.Execute();
continue;
}
}
return sum;
}
}
+9 -15
View File
@@ -1,5 +1,7 @@
using System.Diagnostics;
using MullItOver;
if (args.Length is 0)
{
Console.WriteLine("Please provide a path to the input file.");
@@ -18,21 +20,13 @@ var input = await File.ReadAllTextAsync(args[0]);
var stopwatch = new Stopwatch();
stopwatch.Start();
var instructions = new PuzzleParser().Parse(input);
var parser = new PuzzleParser();
var results = 0;
var instructions = isPart2
? parser.ParseWithConditionals(input)
: parser.Parse(input);
var results = instructions.Execute();
stopwatch.Stop();
Console.WriteLine($"The sum of instructions is {results}. ({stopwatch.ElapsedMilliseconds}ms)");
class PuzzleParser
{
public List<Instruction> Parse(string input)
{
return [];
}
}
class Instruction(int multiplicandOne, int multiplicandTwo)
{
}
Console.WriteLine($"The sum of instructions is {results}. ({stopwatch.ElapsedMilliseconds}ms)");
+55
View File
@@ -0,0 +1,55 @@
using System.Text.RegularExpressions;
namespace MullItOver;
partial class PuzzleParser
{
[GeneratedRegex(@"mul\((\d{1,3}),(\d{1,3})\)")]
private static partial Regex InstructionsRegex();
[GeneratedRegex(@"mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)")]
private static partial Regex InstructionsWithConditionalsRegex();
public List<Instruction> Parse(string input)
{
var matches = InstructionsRegex().Matches(input);
return matches
.Select(Instruction (m) => new MulInstruction(
int.Parse(m.Groups[1].Value),
int.Parse(m.Groups[2].Value)
))
.ToList();
}
public List<Instruction> ParseWithConditionals(string input)
{
var instructions = new List<Instruction>();
var matches = InstructionsWithConditionalsRegex()
.Matches(input)
.ToList();
foreach (var match in matches)
{
var firstGroup = match.Groups[0].Value;
if (firstGroup.Contains("mul"))
{
instructions.Add(new MulInstruction(
int.Parse(match.Groups[1].Value),
int.Parse(match.Groups[2].Value)
));
continue;
}
if (firstGroup.Contains('\''))
{
instructions.Add(new DontInstruction());
continue;
}
instructions.Add(new DoInstruction());
}
return instructions;
}
}