Uploading Days 1-3

This commit is contained in:
James Plante
2023-12-03 15:45:47 -05:00
commit 2b8315b3ab
12 changed files with 376 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
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));
}
}
+6
View File
@@ -0,0 +1,6 @@
using AdventOfCode2023;
var fileContents = File.ReadAllText(Path.GetFullPath("input.txt"));
var lines = fileContents.Split(Environment.NewLine);
Console.WriteLine($"The answer to Part 1 is {Day1.PartOne(lines)}");
Console.WriteLine($"The answer to Part 2 is {Day1.PartTwo(lines)}");
+8
View File
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>