feat: solved day one puzzle

This commit is contained in:
Stevan Freeborn
2023-12-01 21:39:12 -06:00
parent 15dd56f76d
commit 4fb6fbae05
10 changed files with 206 additions and 1044 deletions
+2 -2
View File
@@ -14,8 +14,8 @@ indent_size = 2
#### Core EditorConfig Options #### #### Core EditorConfig Options ####
# Indentation and spacing # Indentation and spacing
indent_size = 4 indent_size = 2
tab_width = 4 tab_width = 2
# New line preferences # New line preferences
end_of_line = crlf end_of_line = crlf
-1000
View File
File diff suppressed because it is too large Load Diff
-28
View File
@@ -1,28 +0,0 @@
# --- Day 1: Trebuchet?! ---
[https://adventofcode.com/2023/day/1](https://adventofcode.com/2023/day/1)
Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems.
You've been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You try to ask why they can't just use a weather machine ("not powerful enough") and where they're even sending you ("the sky") and why your map looks mostly blank ("you sure ask a lot of questions") and hang on did you just say the sky ("of course, where do you think snow comes from") when you realize that the Elves are already loading you into a trebuchet ("please hold still, we need to strap you in").
As they're making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document.
The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.
For example:
```text
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
```
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
Consider your entire calibration document. What is the sum of all of the calibration values?
+1
View File
@@ -1 +1,2 @@
global using Xunit; global using Xunit;
global using FluentAssertions;
@@ -0,0 +1,33 @@
namespace Trebuchet.Tests;
public class PartOnePuzzleSolverTests
{
private readonly PartOnePuzzleSolver _sut = new();
[Theory]
[InlineData("1abc2", 12)]
[InlineData("pqr3stu8vwx", 38)]
[InlineData("a1b2c3d4e5f", 15)]
[InlineData("treb7uchet", 77)]
public void GetCalibrationValue_GivenAStringContainingDigits_ItShouldReturnSumOrFirstAndLastDigit(string input, int expected)
{
var result = _sut.GetCalibrationValue(input);
result.Should().Be(expected);
}
[Theory]
[InlineData(new string[] { "1abc2", "pqr3stu8vwx", "a1b2c3d4e5f", "treb7uchet" }, 142)]
public void SumCalibrationValues_GivenAnArrayOfStrings_ItShouldReturnTheSumOfAllCalibrationValues(string[] input, int expected)
{
var result = _sut.SumCalibrationValues(input);
result.Should().Be(expected);
}
[Fact]
public async Task SumCalibrationValues_GivenAFile_ItShouldReturnTheSumOfAllCalibrationValues()
{
var input = await File.ReadAllLinesAsync("INPUT.txt");
var result = _sut.SumCalibrationValues(input);
result.Should().Be(53194);
}
}
@@ -0,0 +1,41 @@
namespace Trebuchet.Tests;
public class PartTwoPuzzleSolverTests
{
private readonly PartTwoPuzzleSolver _sut = new();
[Theory]
[InlineData("two1nine", 29)]
[InlineData("eightwothree", 83)]
[InlineData("abcone2threexyz", 13)]
[InlineData("xtwone3four", 24)]
[InlineData("4nineeightseven2", 42)]
[InlineData("zoneight234", 14)]
[InlineData("7pqrstsixteen", 76)]
[InlineData("99seven3vdcgvmvxtjtwodc5", 95)]
[InlineData("gpmfhninexxgqr6", 96)]
[InlineData("five3xjzlrmxvqznine", 59)]
[InlineData("nine4vqxmzqxcvfhlm45", 95)]
[InlineData("4nine7oneighthm", 48)]
public void GetCalibrationValue_GivenAStringContainingDigits_ItShouldReturnSumOrFirstAndLastDigit(string input, int expected)
{
var result = _sut.GetCalibrationValue(input);
result.Should().Be(expected);
}
[Theory]
[InlineData(new string[] { "two1nine", "eightwothree", "abcone2threexyz", "xtwone3four", "4nineeightseven2", "zoneight234", "7pqrstsixteen" }, 281)]
public void SumCalibrationValues_GivenAnArrayOfStrings_ItShouldReturnTheSumOfAllCalibrationValues(string[] input, int expected)
{
var result = _sut.SumCalibrationValues(input);
result.Should().Be(expected);
}
[Fact]
public async Task SumCalibrationValues_GivenAFile_ItShouldReturnTheSumOfAllCalibrationValues()
{
var input = await File.ReadAllLinesAsync("INPUT.txt");
var result = _sut.SumCalibrationValues(input);
result.Should().BeLessThan(54249);
}
}
@@ -10,6 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
@@ -26,4 +27,10 @@
<ProjectReference Include="..\Trebuchet\Trebuchet.csproj" /> <ProjectReference Include="..\Trebuchet\Trebuchet.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Include="..\INPUT.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>
-10
View File
@@ -1,10 +0,0 @@
namespace Trebuchet.Tests;
public class UnitTest1
{
[Fact]
public void Test1()
{
}
}
+121 -2
View File
@@ -1,2 +1,121 @@
// See https://aka.ms/new-console-template for more information using System.Text.RegularExpressions;
Console.WriteLine("Hello, World!");
namespace Trebuchet;
public class Program
{
public async static Task<int> Main(string[] args)
{
if (args.Length is 0)
{
Console.WriteLine("Please provide a path to the input file.");
return 1;
}
if (File.Exists(args[0]) is false)
{
Console.WriteLine("The provided file does not exist.");
return 2;
}
IPuzzleSolver puzzleSolver = args.Length > 1 && args[1] == "2"
? new PartTwoPuzzleSolver()
: new PartOnePuzzleSolver();
var input = await File.ReadAllLinesAsync(args[0]);
var result = puzzleSolver.SumCalibrationValues(input);
Console.WriteLine($"The sum of all calibration values is {result}.");
return 0;
}
}
public interface IPuzzleSolver
{
public int SumCalibrationValues(string[] lines);
public int GetCalibrationValue(string line);
}
public class PartOnePuzzleSolver : IPuzzleSolver
{
public int SumCalibrationValues(string[] lines) => lines.Sum(GetCalibrationValue);
public int GetCalibrationValue(string line)
{
if (line.Length is 0)
{
return 0;
}
var numbers = line
.Where(char.IsDigit)
.Select(char.ToString)
.ToList();
var firstNumber = numbers.First();
var lastNumber = numbers.Last();
return int.Parse(firstNumber + lastNumber);
}
}
public class PartTwoPuzzleSolver : IPuzzleSolver
{
private readonly Dictionary<string, string> _validDigitsAsWords = new() {
{ "one", "1" },
{ "two", "2" },
{ "three", "3" },
{ "four", "4" },
{ "five", "5" },
{ "six", "6" },
{ "seven", "7" },
{ "eight", "8" },
{ "nine", "9" },
};
private bool HasValidDigitAsWord(string word, out string match)
{
var matchResult = Regex.Match(word, _validDigitsAsWords.Keys.Aggregate((a, b) => @$"{a}|{b}"));
match = matchResult.Value;
return matchResult.Success;
}
public int SumCalibrationValues(string[] lines) => lines.Sum(GetCalibrationValue);
public int GetCalibrationValue(string line)
{
if (line.Length is 0)
{
return 0;
}
var currentWord = string.Empty;
var numbers = new List<string>();
foreach (var character in line)
{
currentWord += character;
if (char.IsDigit(character))
{
numbers.Add(character.ToString());
currentWord = string.Empty;
}
if (HasValidDigitAsWord(currentWord, out var match))
{
// The last character of the match could be the
// first character of the next valid digit as word
// so we want to preserve it for the next iteration.
numbers.Add(_validDigitsAsWords[match]);
currentWord = currentWord.Replace(match[..^1], string.Empty);
}
}
var firstNumber = numbers.First();
var lastNumber = numbers.Last();
return int.Parse(firstNumber + lastNumber);
}
}
-1
View File
@@ -6,5 +6,4 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
</Project> </Project>