78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
using AdventOfCode.Core.Shared.IO;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace AdventOfCode.Solutions._2024
|
|
{
|
|
public partial class Day03 : IChallange
|
|
{
|
|
public int Year => 2024;
|
|
public int Day => 3;
|
|
|
|
private readonly IInputReader _inputReader;
|
|
|
|
public Day03(IInputReader inputReader)
|
|
{
|
|
_inputReader = inputReader;
|
|
_inputReader.SetInput(this);
|
|
}
|
|
|
|
//161
|
|
//159833790
|
|
public async Task<string> GetSolutionPart1()
|
|
{
|
|
string input = await _inputReader.ReadAsString();
|
|
return ProcessInstructions(input).ToString();
|
|
}
|
|
|
|
//48
|
|
//89349241
|
|
public async Task<string> GetSolutionPart2()
|
|
{
|
|
string input = await _inputReader.ReadAsString();
|
|
return ProcessInstructions(input, true).ToString();
|
|
}
|
|
|
|
private int ProcessInstructions(string instructions, bool extraInstructoins = false)
|
|
{
|
|
bool calc = true;
|
|
int total = 0;
|
|
|
|
MatchCollection collection = MulMatcher().Matches(instructions);
|
|
|
|
foreach (string matchedText in collection.Select(m => m.Value))
|
|
{
|
|
// mul(5,5) is atleast 8 char so any match smaller than 8 is an instruction
|
|
if (matchedText.Length <= 7)
|
|
{
|
|
if (extraInstructoins)
|
|
{
|
|
//do() is only 4 chars, don't() is 7
|
|
calc = matchedText.Length == 4;
|
|
}
|
|
|
|
continue;
|
|
}
|
|
|
|
if (calc)
|
|
{
|
|
total += GetMultiplications(matchedText);
|
|
}
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
private int GetMultiplications(string match)
|
|
{
|
|
MatchCollection collection = NumberMatcher().Matches(match);
|
|
int[] numbers = collection.Select(m => m.Value).Select(int.Parse).ToArray();
|
|
return numbers[0] * numbers[1];
|
|
}
|
|
|
|
[GeneratedRegex(@"(mul\(\d{1,3},\d{1,3}\))|(do\(\))|(don't\(\))")]
|
|
private static partial Regex MulMatcher();
|
|
|
|
[GeneratedRegex(@"(\d{1,3})")]
|
|
private static partial Regex NumberMatcher();
|
|
}
|
|
} |