diff --git a/AdventOfCode/_2023/Day10.cs b/AdventOfCode/_2023/Day10.cs new file mode 100644 index 0000000..b440747 --- /dev/null +++ b/AdventOfCode/_2023/Day10.cs @@ -0,0 +1,83 @@ +using AdventOfCode.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace AdventOfCode._2023 +{ + public class Day1 : AOCDay + { + private Dictionary lookup = new Dictionary() + { + {"zero", 0 }, + {"one", 1 }, + {"two", 2 }, + {"three", 3 }, + {"four", 4 }, + {"five", 5 }, + {"six", 6 }, + {"seven", 7 }, + {"eight", 8 }, + {"nine", 9 }, + }; + protected override AOCResponse ExecutePartA() + { + var totalCount = 0; + foreach (var line in this.GetSplitInput()) + { + totalCount += this._request.Version == AOCVersion.A ? ParseLineIntoNumber(line) : ParseTextLineIntoNumber(line); + } + this.Answer = totalCount; + return this._response; + } + + protected override AOCResponse ExecutePartB() + { + return ExecutePartA(); + } + + private int ParseLineIntoNumber(string line) + { + var firstDigit = line.First(x => char.IsDigit(x)); + var lastDigit = line.Reverse().First(x => char.IsDigit(x)); + Log($"{line} => first: {firstDigit} last: {lastDigit}"); + return int.Parse($"{firstDigit}{lastDigit}"); + } + + private int ParseTextLineIntoNumber(string line) + { + var foundDigits = new List(); + for (int c = 0; c < line.Length; c++) + { + if (char.IsDigit(line[c])) + { + foundDigits.Add(int.Parse(line[c].ToString())); + continue; + } + foreach (var key in lookup.Keys) + { + var length = c + key.Length; + if (length <= line.Length) //Check if we exceeded our line length + { + var section = new String(line.Skip(c).Take(key.Length).ToArray()); + if (section.Equals(key)) + { + foundDigits.Add(lookup[key]); + + //We can't skip the length because eighthree => 83 and sevenine => 79. We only advance one char to fix + //c += key.Length-1; //Outer forloop auto increments one already + break; + } + } + } + } + var firstDigit = foundDigits.First(); + var lastDigit = foundDigits.Last(); + if (firstDigit > 9 || lastDigit > 9) throw new Exception("No digit should be higher than 9"); + var total = int.Parse($"{firstDigit}{lastDigit}"); + Log($"{line} => first: {firstDigit} last: {lastDigit} for total of {total}" ); + return total; + } + } +}