67 lines
1.9 KiB
C#
67 lines
1.9 KiB
C#
namespace AdventOfCodeLibrary._2023
|
|
{
|
|
using AdventOfCodeLibrary.Shared;
|
|
using System.Text.RegularExpressions;
|
|
|
|
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)
|
|
{
|
|
// get all the items
|
|
List<Match> matches = Regex.Matches(line, @"(\d|one|two|three|four|five|six|seven|eight|nine)").OrderBy(x => x.Index).ToList();
|
|
// merge first and last index as one
|
|
string values = GetStringAsNumber(matches[0].Value) + GetStringAsNumber(matches[^1].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;
|
|
}
|
|
}
|
|
}
|
|
}
|