AdventOfCode2023/AdventOfCode2023/Day1/Day1_2.cs

73 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AdventOfCode2023.Day1
{
public class Day1_2 : DayBase
{
string input = string.Empty;
Regex leftSingleDigit = new Regex(@"\d|one|two|three|four|five|six|seven|eight|nine");
Regex rightSingleDigit = new Regex(@"\d|one|two|three|four|five|six|seven|eight|nine", RegexOptions.RightToLeft);
Dictionary<string, string> map = new Dictionary<string, string>() {
{ "one", "1" },
{ "two", "2" },
{ "three", "3" },
{ "four", "4" },
{ "five", "5" },
{ "six", "6" },
{ "seven", "7" },
{ "eight", "8" },
{ "nine", "9" },
};
public Day1_2()
{
input = GetInput("Day1.txt");
}
public Day1_2(string testInput)
{
input = testInput;
}
public override string Execute()
{
var segmentedInput = input.Split("\r\n");
int calibrationSum = 0;
foreach (var segment in segmentedInput)
{
if (!leftSingleDigit.IsMatch(segment))
{
return $"segment: {segment} does not contain a digit!";
}
var leftMatch = leftSingleDigit.Match(segment);
var rightMatch = rightSingleDigit.Match(segment);
var joinedString = string.Join("", leftMatch.Value ?? "", rightMatch.Value ?? "");
var digitizedString = joinedString;
foreach (var item in map)
{
digitizedString = digitizedString.Replace(item.Key, item.Value);
}
if (int.TryParse(digitizedString, out var calibrationValue))
{
calibrationSum += calibrationValue;
}
else
{
return $"Could not parse segment: {digitizedString} to int!";
}
}
return calibrationSum.ToString();
}
}
}