-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day1.cs
69 lines (60 loc) · 1.64 KB
/
Day1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Text.RegularExpressions;
namespace AdventOfCode2023
{
internal class Day1
{
static readonly Dictionary<string, string> wordNumbers = new(){
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"five", "5"},
{"six", "6"},
{"seven", "7"},
{"eight", "8"},
{"nine", "9"}
};
public static void RunPuzzle1()
{
string[] lines = File.ReadAllLines(@"Day1-Input.txt");
int sumCalibration = 0;
foreach (string line in lines)
{
string twoDigitString = line.ToCharArray().First(char.IsNumber).ToString() + line.ToCharArray().Last(char.IsNumber);
sumCalibration += int.Parse(twoDigitString);
}
Console.WriteLine("Answer Puzzle 1: " + sumCalibration);
}
public static void RunPuzzle2()
{
string[] lines = File.ReadAllLines(@"Day1-Input.txt");
int sumCalibration = 0;
string digitOne, digitTwo = "";
foreach (string line in lines)
{
Match matches = Regex.Match(line, "(one|two|three|four|five|six|seven|eight|nine|\\d)");
digitOne = matches.Value;
for (int i = 1; i <= line.Length; i++)
{
string endString = line[^i..];
matches = Regex.Match(endString, "(one|two|three|four|five|six|seven|eight|nine|\\d)");
if (!string.IsNullOrEmpty(matches.Value))
{
digitTwo = matches.Value;
break;
}
}
if (!int.TryParse(digitOne, out int firstDigit))
{
digitOne = wordNumbers[digitOne];
}
if (!int.TryParse(digitTwo, out int secondDigit))
{
digitTwo = wordNumbers[digitTwo];
}
sumCalibration += int.Parse(digitOne + digitTwo);
}
Console.WriteLine("Answer Puzzle 2: " + sumCalibration);
}
}
}