AdventOfCode/AdventOfCode.Solutions/2023/Day 01/Day01.cs
2023-12-04 21:05:23 +01:00

65 lines
2.5 KiB
C#

using AdventOfCode.Core;
using System.Text.RegularExpressions;
namespace AdventOfCode.Solutions._2023
{
public class Day01(InputReader reader) : IChallange
{
private readonly List<string> NumberMapping = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
private InputReader _inputReader = reader;
public async Task<string> GetSolutionPart1()
{
int sum = 0;
await foreach(string line in _inputReader.ReadAsStringLine())
{
// get all the numers
MatchCollection collection = Regex.Matches(line, @"\d");
// merge first and last index as one
string values = collection[0].Value + collection[^1].Value;
// make an int
sum += int.Parse(values);
}
return sum.ToString();
}
public async Task<string> GetSolutionPart2()
{
int sum = 0;
await foreach (string line in _inputReader.ReadAsStringLine())
{
string regex = @"(\d|one|two|three|four|five|six|seven|eight|nine)";
MatchCollection matchCollection = Regex.Matches(line, @"(\d)");
List<Match> captures = matchCollection.ToList();
// replace the text with numbers
captures.AddRange(Regex.Matches(line, @"(one)"));
captures.AddRange(Regex.Matches(line, @"(two)"));
captures.AddRange(Regex.Matches(line, @"(three)"));
captures.AddRange(Regex.Matches(line, @"(four)"));
captures.AddRange(Regex.Matches(line, @"(five)"));
captures.AddRange(Regex.Matches(line, @"(six)"));
captures.AddRange(Regex.Matches(line, @"(seven)"));
captures.AddRange(Regex.Matches(line, @"(eight)"));
captures.AddRange(Regex.Matches(line, @"(nine)"));
captures = captures.OrderBy(x => x.Index).ToList();
// merge first and last index as one
string values = GetStringAsNumber(captures.First().Value) + GetStringAsNumber(captures.Last().Value);
// make an int
sum += int.Parse(values);
}
return sum.ToString();
}
private string GetStringAsNumber(string value)
{
return value.Length == 1 ? value : NumberMapping.IndexOf(value).ToString();
}
}
}