71 lines
2.6 KiB
C#
71 lines
2.6 KiB
C#
using AdventOfCode.Core.Shared.IO;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace AdventOfCode.Solutions._2023
|
|
{
|
|
public class Day01 : IChallange
|
|
{
|
|
public int Year => 2023;
|
|
public int Day => 1;
|
|
|
|
private readonly List<string> NumberMapping = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
|
|
private readonly IInputReader _inputReader;
|
|
|
|
public Day01(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
|
|
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())
|
|
{
|
|
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();
|
|
}
|
|
}
|
|
} |