80 lines
2.5 KiB
C#
80 lines
2.5 KiB
C#
using System.Text.RegularExpressions;
|
|
|
|
namespace AdventOfCode.Solutions._2023
|
|
{
|
|
public class Day01Part2 : Answerable
|
|
{
|
|
public override int Year { get; set; } = 2023;
|
|
public override int Day { get; set; } = 1;
|
|
public override int Part { get; set; } = 2;
|
|
|
|
public override string GetAnswer(byte[] data)
|
|
{
|
|
return GetAsStringArray(data)
|
|
.Select(GetValueFromLine)
|
|
.Sum()
|
|
.ToString();
|
|
}
|
|
|
|
private int GetValueFromLine(string line)
|
|
{
|
|
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
|
|
return int.Parse(values);
|
|
}
|
|
|
|
private string GetStringAsNumber(string value)
|
|
{
|
|
switch(value)
|
|
{
|
|
case "one":
|
|
case "1":
|
|
return "1";
|
|
case "two":
|
|
case "2":
|
|
return "2";
|
|
case "three":
|
|
case "3":
|
|
return "3";
|
|
case "four":
|
|
case "4":
|
|
return "4";
|
|
case "five":
|
|
case "5":
|
|
return "5";
|
|
case "six":
|
|
case "6":
|
|
return "6";
|
|
case "seven":
|
|
case "7":
|
|
return "7";
|
|
case "eight":
|
|
case "8":
|
|
return "8";
|
|
case "nine":
|
|
case "9":
|
|
return "9";
|
|
default:
|
|
return string.Empty;
|
|
}
|
|
}
|
|
}
|
|
}
|