AdventOfCode/AdventOfCode.Solutions/2023/Day 02/Day02.cs
2024-12-01 10:17:24 +01:00

88 lines
2.9 KiB
C#

using AdventOfCode.Core.Shared.IO;
using System.Text.RegularExpressions;
namespace AdventOfCode.Solutions._2023
{
public class Day02: IChallange
{
public int Year => 2023;
public int Day => 2;
private readonly IInputReader _inputReader;
public Day02(IInputReader inputReader)
{
_inputReader = inputReader;
_inputReader.SetInput(this);
}
public async Task<string> GetSolutionPart1()
{
int sum = 0;
await foreach(string line in _inputReader.ReadAsStringLine())
{
// get all the numers
string gameId = line.Split(':')[0].Split(' ')[1];
string[] dicePulls = line.Split(':')[1].Split(';');
bool impossible = false;
// parse the pulls
foreach (string dicePull in dicePulls)
{
// regex the pull
MatchCollection dice = Regex.Matches(dicePull, "(\\d+) (g|r|b)");
foreach (Match match in dice)
{
string[] splitted = match.Value.Split(' ');
int ammount = int.Parse(splitted[0]);
if (ammount <= 12) // pass for all dice
continue;
if (ammount > 14 // fail for any dice set
|| (splitted[1] == "r" && ammount > 12)
|| (splitted[1] == "g" && ammount > 13))
impossible = true; // not possible
if (impossible) break;
}
if (impossible) break;
}
if (!impossible)
{
sum += int.Parse(gameId);
}
}
return sum.ToString();
}
public async Task<string> GetSolutionPart2()
{
int sum = 0;
await foreach (string line in _inputReader.ReadAsStringLine())
{
// get all the numers
string dicePulls = line.Split(':')[1];
// parse the pulls
MatchCollection dice = Regex.Matches(dicePulls, "(\\d+) (g|r|b)");
int red = 0, green = 0, blue = 0;
foreach (Match match in dice)
{
string[] splitted = match.Value.Split(' ');
int ammount = int.Parse(splitted[0]);
if (splitted[1] == "r" && ammount > red) { red = ammount; }
else if (splitted[1] == "g" && ammount > green) { green = ammount; }
else if (splitted[1] == "b" && ammount > blue) { blue = ammount; }
}
sum += red * green * blue;
}
return sum.ToString();
}
}
}