AdventOfCode/AdventOfCode.Solutions/2023/Day 19/Day19.cs
2023-12-19 21:37:19 +01:00

138 lines
4.2 KiB
C#

using System.Reflection.Metadata.Ecma335;
using System.Text.RegularExpressions;
namespace AdventOfCode.Solutions._2023
{
public class Day19(InputReader reader) : IChallange
{
private InputReader _inputReader = reader;
public async Task<string> GetSolutionPart1()
{
List<InstructionSet> instructions = [];
List<Part> parts = [];
bool instructionsDone = false;
await foreach(string line in _inputReader.ReadAsStringLine())
{
if (string.IsNullOrWhiteSpace(line))
{
instructionsDone = true;
continue;
}
if (!instructionsDone)
{
instructions.Add(ParseLine(line));
}
else
{
int[] values = Regex.Matches(line,@"\d+")
.SelectMany(match => match.Captures.Select(cap => cap.Value))
.Select(int.Parse)
.ToArray();
parts.Add(new(values[0], values[1], values[2], values[3]));
}
}
List<Part> acceptedPart = [];
foreach(Part part in parts)
{
InstructionSet set = instructions.First(set => set.Name == "in");
var processResult = string.Empty;
while (true)
{
processResult = set.Process(part);
if (processResult.Length == 1)
break;
set = instructions.First(set => set.Name == processResult);
}
if (processResult == "A")
{
acceptedPart.Add(part);
}
}
return acceptedPart.Sum(p => p.Sum).ToString();
}
public async Task<string> GetSolutionPart2()
{
return string.Empty;
}
internal static InstructionSet ParseLine(string line)
{
string[] nameSplit = line.Split('{');
// build the instructions
List<Instruction> instructions = [];
foreach (string instructionText in nameSplit[1][..^1].Split(','))
{
if (!instructionText.Any(c => c ==':'))
{
instructions.Add(new() { ValueTrue = instructionText });
continue;
}
Instruction instruction = new()
{
Category = instructionText[0],
Operator = instructionText[1],
CompairValue = int.Parse(instructionText[2..instructionText.IndexOf(':')]),
ValueTrue = instructionText[(instructionText.IndexOf(':') + 1)..]
};
instructions.Add(instruction);
}
return new() { Name = nameSplit[0], Instructions = instructions };
}
}
internal class InstructionSet
{
public string Name { get; set; }
public List<Instruction> Instructions { get; set; }
public string Process(Part part)
{
for(int instructionIndex = 0; instructionIndex < Instructions.Count - 1; instructionIndex++)
{
if (Instructions[instructionIndex].Matches(part))
return Instructions[instructionIndex].ValueTrue;
}
return Instructions[^1].ValueTrue;
}
}
internal class Instruction
{
public char Category;
public char Operator;
public int CompairValue;
public string ValueTrue;
public bool Matches(Part part)
{
int value = 0;
switch(Category)
{
case 'x': value = part.x; break;
case 'm': value = part.m; break;
case 'a': value = part.a; break;
case 's': value = part.s; break;
}
return Operator == '>' ? value > CompairValue : value < CompairValue;
}
}
public record Part(int x, int m, int a, int s)
{
public int Sum => x + m + a + s;
}
}