2023-12-03 15:45:47 -05:00

89 lines
2.5 KiB
C#

namespace AdventOfCode2023;
using System.Text.RegularExpressions;
public class Day1
{
private static int artsyStringToInt(string s)
{
var matches = Regex.Matches(s, @"[0-9]");
var result = -1;
if (matches.Count == 1)
{
result = int.Parse($"{matches[0]}{matches[0]}");
}
else if (matches.Count > 1)
{
result = int.Parse($"{matches[0]}{matches[matches.Count - 1]}");
}
return result;
}
private static bool tryResolveNumericValue(string digit, out int? result)
{
var nameToDigit = new Dictionary<string, int>() {
{"one", 1},
{"two", 2},
{"three", 3},
{"four", 4},
{"five", 5},
{"six", 6},
{"seven", 7},
{"eight", 8},
{"nine", 9}
};
var matches = Regex.Matches(digit, @"one|two|three|four|five|six|seven|eight|nine");
if (matches.Count > 0)
{
result = nameToDigit[matches[0].ToString()];
return true;
}
result = null;
return false;
}
private static int searchStringForDigit(string s, bool digitReversed = false)
{
var currentWord = "";
foreach (var c in s)
{
if (Char.IsDigit(c))
{
return int.Parse(c.ToString());
}
else if (Char.IsLetter(c))
{
int? foundDigit;
if (digitReversed)
{
currentWord = c.ToString() + currentWord;
}
else
{
currentWord = currentWord + c.ToString();
}
if (tryResolveNumericValue(currentWord, out foundDigit) && foundDigit != null)
{
return (int)foundDigit; // VSCode needs a cast here for some reason
}
}
}
return -1;
}
private static int artsyStringToIntPartTwo(string s)
{
var reversedString = new string(s.Reverse().ToArray());
return int.Parse($"{searchStringForDigit(s)}{searchStringForDigit(reversedString, true)}");
}
public static int PartOne(IList<string> lines)
{
return lines.Aggregate(0, (current, line) => current + artsyStringToInt(line));
}
public static int PartTwo(IList<string> lines)
{
return lines.Aggregate(0, (current, line) => current + artsyStringToIntPartTwo(line));
}
}