From a8ae57bc8c6270862a8784f5e163c21cd5e2dde0 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Mon, 4 Dec 2023 23:18:11 -0600 Subject: [PATCH 1/7] chore: scaffold for day 5 puzzle --- 05/IYGASAF.Tests/GlobalUsings.cs | 2 ++ 05/IYGASAF.Tests/IYGASAF.Tests.csproj | 36 +++++++++++++++++++++++++++ 05/IYGASAF.Tests/UnitTest1.cs | 10 ++++++++ 05/IYGASAF/IYGASAF.csproj | 10 ++++++++ 05/IYGASAF/Program.cs | 2 ++ AdventOfCode2023.sln | 16 ++++++++++++ 6 files changed, 76 insertions(+) create mode 100644 05/IYGASAF.Tests/GlobalUsings.cs create mode 100644 05/IYGASAF.Tests/IYGASAF.Tests.csproj create mode 100644 05/IYGASAF.Tests/UnitTest1.cs create mode 100644 05/IYGASAF/IYGASAF.csproj create mode 100644 05/IYGASAF/Program.cs diff --git a/05/IYGASAF.Tests/GlobalUsings.cs b/05/IYGASAF.Tests/GlobalUsings.cs new file mode 100644 index 0000000..7fef4b0 --- /dev/null +++ b/05/IYGASAF.Tests/GlobalUsings.cs @@ -0,0 +1,2 @@ +global using Xunit; +global using FluentAssertions; \ No newline at end of file diff --git a/05/IYGASAF.Tests/IYGASAF.Tests.csproj b/05/IYGASAF.Tests/IYGASAF.Tests.csproj new file mode 100644 index 0000000..c1844dc --- /dev/null +++ b/05/IYGASAF.Tests/IYGASAF.Tests.csproj @@ -0,0 +1,36 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + PreserveNewest + + + + diff --git a/05/IYGASAF.Tests/UnitTest1.cs b/05/IYGASAF.Tests/UnitTest1.cs new file mode 100644 index 0000000..6c2a1c6 --- /dev/null +++ b/05/IYGASAF.Tests/UnitTest1.cs @@ -0,0 +1,10 @@ +namespace IYGASAF.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} \ No newline at end of file diff --git a/05/IYGASAF/IYGASAF.csproj b/05/IYGASAF/IYGASAF.csproj new file mode 100644 index 0000000..2150e37 --- /dev/null +++ b/05/IYGASAF/IYGASAF.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + + diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs new file mode 100644 index 0000000..3751555 --- /dev/null +++ b/05/IYGASAF/Program.cs @@ -0,0 +1,2 @@ +// See https://aka.ms/new-console-template for more information +Console.WriteLine("Hello, World!"); diff --git a/AdventOfCode2023.sln b/AdventOfCode2023.sln index 3e793ae..2c0a187 100644 --- a/AdventOfCode2023.sln +++ b/AdventOfCode2023.sln @@ -27,6 +27,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scratchcards", "04\Scratchc EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scratchcards.Tests", "04\Scratchcards.Tests\Scratchcards.Tests.csproj", "{FF8A5512-85FD-45E7-9F97-EC528465949C}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "05", "05", "{5067FD6B-8F03-4502-AB83-8A391D801B47}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IYGASAF", "05\IYGASAF\IYGASAF.csproj", "{417E0408-31C8-4945-B684-5004233D6AF4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IYGASAF.Tests", "05\IYGASAF.Tests\IYGASAF.Tests.csproj", "{CB90004D-9420-4411-9110-B50274537FE5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -68,6 +74,14 @@ Global {FF8A5512-85FD-45E7-9F97-EC528465949C}.Debug|Any CPU.Build.0 = Debug|Any CPU {FF8A5512-85FD-45E7-9F97-EC528465949C}.Release|Any CPU.ActiveCfg = Release|Any CPU {FF8A5512-85FD-45E7-9F97-EC528465949C}.Release|Any CPU.Build.0 = Release|Any CPU + {417E0408-31C8-4945-B684-5004233D6AF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {417E0408-31C8-4945-B684-5004233D6AF4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {417E0408-31C8-4945-B684-5004233D6AF4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {417E0408-31C8-4945-B684-5004233D6AF4}.Release|Any CPU.Build.0 = Release|Any CPU + {CB90004D-9420-4411-9110-B50274537FE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CB90004D-9420-4411-9110-B50274537FE5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CB90004D-9420-4411-9110-B50274537FE5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CB90004D-9420-4411-9110-B50274537FE5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {3F8EAC09-4BC7-43AA-B72B-48DDD2710F6D} = {8C29858C-623A-461A-BF0B-254E151CD9C2} @@ -78,5 +92,7 @@ Global {FEE9253C-A56B-4735-BDB3-C62220C5B1B1} = {EA04152D-316A-4AA4-9BC1-57F6A9F3CD4E} {B58CF14B-97A1-45F6-967F-29FA82DAFD0F} = {522D6D1E-54AD-4479-BB78-0AB5D7493EFC} {FF8A5512-85FD-45E7-9F97-EC528465949C} = {522D6D1E-54AD-4479-BB78-0AB5D7493EFC} + {417E0408-31C8-4945-B684-5004233D6AF4} = {5067FD6B-8F03-4502-AB83-8A391D801B47} + {CB90004D-9420-4411-9110-B50274537FE5} = {5067FD6B-8F03-4502-AB83-8A391D801B47} EndGlobalSection EndGlobal From d70d1c8bce16f3a75dce2f3594a1695a91830341 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Tue, 5 Dec 2023 16:17:38 -0600 Subject: [PATCH 2/7] chore: stub out program.cs --- 05/IYGASAF/Program.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs index 3751555..ebf228a 100644 --- a/05/IYGASAF/Program.cs +++ b/05/IYGASAF/Program.cs @@ -1,2 +1,9 @@ -// See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); +namespace IYGASAF; + +public class Program +{ + public static async Task Main(string[] args) + { + return await Task.FromResult(0); + } +} \ No newline at end of file From e4ff5ed4c44baebd50c63acbb43cb270c4e8fb43 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Tue, 5 Dec 2023 19:52:23 -0600 Subject: [PATCH 3/7] feat: solve part 1 of puzzle 5 --- 05/IYGASAF.Tests/AlmanacTests.cs | 140 ++++++++++++++++ 05/IYGASAF.Tests/MapTests.cs | 275 +++++++++++++++++++++++++++++++ 05/IYGASAF.Tests/RangeTests.cs | 23 +++ 05/IYGASAF.Tests/UnitTest1.cs | 10 -- 05/IYGASAF/Program.cs | 154 ++++++++++++++++- 5 files changed, 591 insertions(+), 11 deletions(-) create mode 100644 05/IYGASAF.Tests/AlmanacTests.cs create mode 100644 05/IYGASAF.Tests/MapTests.cs create mode 100644 05/IYGASAF.Tests/RangeTests.cs delete mode 100644 05/IYGASAF.Tests/UnitTest1.cs diff --git a/05/IYGASAF.Tests/AlmanacTests.cs b/05/IYGASAF.Tests/AlmanacTests.cs new file mode 100644 index 0000000..9d6b07c --- /dev/null +++ b/05/IYGASAF.Tests/AlmanacTests.cs @@ -0,0 +1,140 @@ +namespace IYGASAF.Tests; + +public class AlmanacTests +{ + private readonly Almanac _sut = TestData.TestAlmanac; + + [Theory] + [MemberData(nameof(TestData.TestAlmanacData), MemberType = typeof(TestData))] + public void Parse_WhenGivenValidAlmanac_ItShouldReturnExpectedAlmanac(string[] almanac, Almanac expected) + { + var result = Almanac.Parse(almanac); + result.Should().BeEquivalentTo(expected); + } + + [Theory] + [InlineData(79, 82)] + [InlineData(14, 43)] + [InlineData(55, 86)] + [InlineData(13, 35)] + public void GetSeedLocation_WhenGivenValidSeed_ItShouldReturnExpectedLocation(int seed, int expected) + { + var result = _sut.GetSeedLocation(seed); + result.Should().Be(expected); + } + + [Fact] + public void GetLowestSeedLocation_WhenCalled_ItShouldReturnExpectedLocation() + { + var result = _sut.GetLowestSeedLocation(); + result.Should().Be(35); + } + + [Fact] + public void GetLowestSeedLocation_WhenCalledWithPuzzleInput_ItShouldReturnExpectedLocation() + { + var almanac = File.ReadAllLines("INPUT.txt"); + var sut = Almanac.Parse(almanac); + var result = sut.GetLowestSeedLocation(); + result.Should().Be(806029445); + } + + public static class TestData + { + public static readonly Almanac TestAlmanac = + new( + [ + 79, + 14, + 55, + 13, + ], + [ + new( + [ + new(2, 98, 50), + new(48, 50, 52), + ] + ), + new( + [ + new(37, 15, 0), + new(2, 52, 37), + new(15, 0, 39), + ] + ), + new( + [ + new(8, 53, 49), + new(42, 11, 0), + new(7, 0, 42), + new(4, 7, 57), + ] + ), + new( + [ + new(7, 18, 88), + new(70, 25, 18), + ] + ), + new( + [ + new(23, 77, 45), + new(19, 45, 81), + new(13, 64, 68), + ] + ), + new( + [ + new(1, 69, 0), + new(69, 0, 1), + ] + ), + new( + [ + new(37, 56, 60), + new(4, 93, 56), + ] + ), + ] + ); + + public static readonly IEnumerable TestAlmanacData = + new List + { + new object[] + { + new string[] + { + "seeds: 79 14 55 13", + "seed-to-soil map:", + "50 98 2", + "52 50 48", + "soil-to-fertilizer map:", + "0 15 37", + "37 52 2", + "39 0 15", + "fertilizer-to-water map:", + "49 53 8", + "0 11 42", + "42 0 7", + "57 7 4", + "water-to-light map:", + "88 18 7", + "18 25 70", + "light-to-temperature map:", + "45 77 23", + "81 45 19", + "68 64 13", + "temperature-to-humidity map:", + "0 69 1", + "1 0 69", + "humidity-to-location map:", + "60 56 37", + "56 93 4", + }, + TestAlmanac, + }, + }; + } +} \ No newline at end of file diff --git a/05/IYGASAF.Tests/MapTests.cs b/05/IYGASAF.Tests/MapTests.cs new file mode 100644 index 0000000..7b02f32 --- /dev/null +++ b/05/IYGASAF.Tests/MapTests.cs @@ -0,0 +1,275 @@ +namespace IYGASAF.Tests; + +public class MapTests +{ + [Theory] + [MemberData(nameof(TestData.ParseMapData), MemberType = typeof(TestData))] + public void Parse_WhenGivenValidMap_ItShouldReturnExpectedMap(string[] ranges, Map expected) + { + var result = Map.Parse(ranges); + result.Should().BeEquivalentTo(expected); + } + + [Theory] + [MemberData(nameof(TestData.ConvertData), MemberType = typeof(TestData))] + public void ConvertSourceToDestination_WhenGivenValidSourceValue_ItShouldReturnExpectedDestinationValue(Map map, int sourceValue, int expected) + { + var result = map.ConvertSourceToDestination(sourceValue); + result.Should().Be(expected); + } + + public static class TestData + { + private static readonly Map TestSeedToSoilMap = new( + [ + new(2, 98, 50), + new(48, 50, 52), + ] + ); + + private static readonly Map TestSoilToFertilizerMap = new( + [ + new(37, 15, 0), + new(2, 52, 37), + new(15, 0, 39), + ] + ); + + private static readonly Map TestFertilizerToWaterMap = new( + [ + new(8, 53, 49), + new(42, 11, 0), + new(7, 0, 42), + new(4, 7, 57), + ] + ); + + private static readonly Map TestWaterToLightMap = new( + [ + new(7, 18, 88), + new(70, 25, 18), + ] + ); + + private static readonly Map TestLightToTemperatureMap = new( + [ + new(23, 77, 45), + new(19, 45, 81), + new(13, 64, 68), + ] + ); + + private static readonly Map TestTemperatureToHumidityMap = new( + [ + new(1, 69, 0), + new(69, 0, 1), + ] + ); + + private static readonly Map TestHumidityToLocationMap = new( + [ + new(37, 56, 60), + new(4, 93, 56), + ] + ); + + public static IEnumerable ConvertData => + new List + { + new object[] + { + TestSeedToSoilMap, + 79, + 81, + }, + new object[] + { + TestSeedToSoilMap, + 14, + 14, + }, + new object[] + { + TestSeedToSoilMap, + 55, + 57, + }, + new object[] + { + TestSeedToSoilMap, + 13, + 13, + }, + new object[] + { + TestSoilToFertilizerMap, + 81, + 81, + }, + new object[] + { + TestSoilToFertilizerMap, + 14, + 53, + }, + new object[] + { + TestSoilToFertilizerMap, + 57, + 57, + }, + new object[] + { + TestSoilToFertilizerMap, + 13, + 52, + }, + new object[] + { + TestFertilizerToWaterMap, + 81, + 81, + }, + new object[] + { + TestFertilizerToWaterMap, + 53, + 49, + }, + new object[] + { + TestFertilizerToWaterMap, + 57, + 53, + }, + new object[] + { + TestFertilizerToWaterMap, + 52, + 41, + }, + new object[] + { + TestWaterToLightMap, + 81, + 74, + }, + new object[] + { + TestWaterToLightMap, + 49, + 42, + }, + new object[] + { + TestWaterToLightMap, + 53, + 46, + }, + new object[] + { + TestWaterToLightMap, + 41, + 34, + }, + new object[] + { + TestLightToTemperatureMap, + 74, + 78, + }, + new object[] + { + TestLightToTemperatureMap, + 42, + 42, + }, + new object[] + { + TestLightToTemperatureMap, + 46, + 82, + }, + new object[] + { + TestLightToTemperatureMap, + 34, + 34, + }, + new object[] + { + TestTemperatureToHumidityMap, + 78, + 78, + }, + new object[] + { + TestTemperatureToHumidityMap, + 42, + 43, + }, + new object[] + { + TestTemperatureToHumidityMap, + 82, + 82, + }, + new object[] + { + TestTemperatureToHumidityMap, + 34, + 35, + }, + new object[] + { + TestHumidityToLocationMap, + 78, + 82, + }, + new object[] + { + TestHumidityToLocationMap, + 43, + 43, + }, + new object[] + { + TestHumidityToLocationMap, + 82, + 86, + }, + new object[] + { + TestHumidityToLocationMap, + 35, + 35, + }, + }; + + public static IEnumerable ParseMapData => + new List + { + new object[] + { + new string[] { "50 98 2", "52 50 48" }, + new Map( + [ + new(2, 98, 50), + new(48, 50, 52) + ] + ), + }, + new object[] + { + new string[] {"0 15 37", "37 52 2", "39 0 15"}, + new Map( + [ + new(37, 15, 0), + new(2, 52, 37), + new(15, 0, 39), + ] + ), + } + }; + } +} \ No newline at end of file diff --git a/05/IYGASAF.Tests/RangeTests.cs b/05/IYGASAF.Tests/RangeTests.cs new file mode 100644 index 0000000..385bacc --- /dev/null +++ b/05/IYGASAF.Tests/RangeTests.cs @@ -0,0 +1,23 @@ +namespace IYGASAF.Tests; + +public class RangeTests +{ + [Theory] + [MemberData(nameof(TestData.ParseRangeData), MemberType = typeof(TestData))] + public void Parse_WhenGivenValidRange_ItShouldReturnExpectedRange(string range, Range expected) + { + var result = Range.Parse(range); + result.Should().BeEquivalentTo(expected); + } + + + public static class TestData + { + public static IEnumerable ParseRangeData => + new List + { + new object[] { "50 98 2", new Range(2, 98, 50) }, + new object[] { "52 50 48", new Range(48, 50, 52) }, + }; + } +} \ No newline at end of file diff --git a/05/IYGASAF.Tests/UnitTest1.cs b/05/IYGASAF.Tests/UnitTest1.cs deleted file mode 100644 index 6c2a1c6..0000000 --- a/05/IYGASAF.Tests/UnitTest1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace IYGASAF.Tests; - -public class UnitTest1 -{ - [Fact] - public void Test1() - { - - } -} \ No newline at end of file diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs index ebf228a..f121d98 100644 --- a/05/IYGASAF/Program.cs +++ b/05/IYGASAF/Program.cs @@ -4,6 +4,158 @@ public class Program { public static async Task Main(string[] args) { - return await Task.FromResult(0); + 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; + } + + + var input = await File.ReadAllLinesAsync(args[0]); + var result = Almanac.Parse(input).GetLowestSeedLocation(); + + Console.WriteLine($"The lowest seed location is {result}."); + + return (int)result; + } +} + +public class Almanac( + List seeds, + List maps +) +{ + public List Seeds { get; init; } = seeds; + public List Maps { get; init; } = maps; + + public long GetSeedLocation(long seed) => Maps.Aggregate( + seed, + (currentSeed, map) => map.ConvertSourceToDestination(currentSeed) + ); + + public long GetLowestSeedLocation() => Seeds + .Select(GetSeedLocation) + .Min(); + + public static Almanac Parse(string[] almanac) + { + var seedsString = almanac[0].Split(':')[1]; + var seeds = seedsString + .Split( + ' ', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ) + .Select(long.Parse) + .ToList(); + + var maps = new List(); + var ranges = new List(); + + for (int i = 1; i < almanac.Length; i++) + { + var currentLine = almanac[i]; + + if (string.IsNullOrWhiteSpace(currentLine)) + { + continue; + } + + if (currentLine.Contains(':')) + { + if (ranges.Count is not 0) + { + maps.Add(Map.Parse([.. ranges])); + ranges.Clear(); + } + continue; + } + + ranges.Add(currentLine); + + if (i == almanac.Length - 1) + { + maps.Add(Map.Parse([.. ranges])); + } + } + + return new Almanac( + seeds, + maps + ); + } +} + +public class Map( + List ranges +) +{ + public List Ranges { get; init; } = ranges; + + public static Map Parse(string[] ranges) => + new( + ranges.Select(Range.Parse).ToList() + ); + + public Range? GetSourceRange(long sourceValue) => + Ranges + .Where(range => range.SourceStart <= sourceValue && range.SourceEnd >= sourceValue) + .FirstOrDefault(); + + public long ConvertSourceToDestination(long valueToConvert) + { + var sourceRange = GetSourceRange(valueToConvert); + + if (sourceRange is null) + { + return valueToConvert; + } + + var sourceToDestinationOffset = Math.Abs(sourceRange.SourceStart - sourceRange.DestinationStart); + + return sourceRange.DestinationStart <= sourceRange.SourceStart + ? valueToConvert - sourceToDestinationOffset + : valueToConvert + sourceToDestinationOffset; + } +} + +public class Range( + long rangeLength, + long sourceStart, + long destinationStart +) +{ + public long RangeLength { get; init; } = rangeLength; + public long SourceStart { get; init; } = sourceStart; + public long SourceEnd => SourceStart + RangeLength - 1; + public long DestinationStart { get; init; } = destinationStart; + public long DestinationEnd => DestinationStart + RangeLength - 1; + + public static Range Parse(string range) + { + var parts = range.Split( + ' ', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ); + + if (parts.Length is not 3 || parts.Any(part => long.TryParse(part, out _) is false)) + { + throw new ArgumentException("Range must be in the format of 'DestinationRangeStart:long SourceRangeStart:long RangeLength:long'"); + } + + var rangeLength = long.Parse(parts[2]); + var sourceStart = long.Parse(parts[1]); + var destinationStart = long.Parse(parts[0]); + + return new Range( + rangeLength, + sourceStart, + destinationStart + ); } } \ No newline at end of file From a28beda20031075b0cd3705294f9176823af783f Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:05:10 -0600 Subject: [PATCH 4/7] feat: trying to solve part 2 --- 05/IYGASAF.Tests/AlmanacTests.cs | 63 ++++++++++++++++-- 05/IYGASAF/Program.cs | 109 +++++++++++++++++++++++++++---- 2 files changed, 156 insertions(+), 16 deletions(-) diff --git a/05/IYGASAF.Tests/AlmanacTests.cs b/05/IYGASAF.Tests/AlmanacTests.cs index 9d6b07c..80e113b 100644 --- a/05/IYGASAF.Tests/AlmanacTests.cs +++ b/05/IYGASAF.Tests/AlmanacTests.cs @@ -2,8 +2,6 @@ namespace IYGASAF.Tests; public class AlmanacTests { - private readonly Almanac _sut = TestData.TestAlmanac; - [Theory] [MemberData(nameof(TestData.TestAlmanacData), MemberType = typeof(TestData))] public void Parse_WhenGivenValidAlmanac_ItShouldReturnExpectedAlmanac(string[] almanac, Almanac expected) @@ -19,17 +17,27 @@ public class AlmanacTests [InlineData(13, 35)] public void GetSeedLocation_WhenGivenValidSeed_ItShouldReturnExpectedLocation(int seed, int expected) { - var result = _sut.GetSeedLocation(seed); + var sut = TestData.TestAlmanac; + var result = sut.GetSeedLocation(seed); result.Should().Be(expected); } [Fact] public void GetLowestSeedLocation_WhenCalled_ItShouldReturnExpectedLocation() { - var result = _sut.GetLowestSeedLocation(); + var sut = TestData.TestAlmanac; + var result = sut.GetLowestSeedLocation(); result.Should().Be(35); } + [Fact] + public void GetLowestSeedLocation_WhenCalledAndSeedsAreParsedAsRanges_ItShouldReturnExpectedLocation() + { + var sut = Almanac.Parse(TestData.TestAlmanacInput); + var result = sut.GetLowestSeedLocation(true); + result.Should().Be(46); + } + [Fact] public void GetLowestSeedLocation_WhenCalledWithPuzzleInput_ItShouldReturnExpectedLocation() { @@ -39,6 +47,19 @@ public class AlmanacTests result.Should().Be(806029445); } + [Fact] + public void ParseSeedsAsRanges_WhenGivenValidSeedsString_ItShouldReturnExpectedSeeds() + { + var seedsString = "79 14 55 13"; + var expected = new List + { + new(79, 14), + new(55, 13), + }; + var result = Almanac.ParseSeedsAsRanges(seedsString); + result.Should().BeEquivalentTo(expected); + } + public static class TestData { public static readonly Almanac TestAlmanac = @@ -49,6 +70,10 @@ public class AlmanacTests 55, 13, ], + [ + new(79, 14), + new(55, 13), + ], [ new( [ @@ -99,6 +124,36 @@ public class AlmanacTests ] ); + public static readonly string[] TestAlmanacInput = + [ + "seeds: 79 14 55 13", + "seed-to-soil map:", + "50 98 2", + "52 50 48", + "soil-to-fertilizer map:", + "0 15 37", + "37 52 2", + "39 0 15", + "fertilizer-to-water map:", + "49 53 8", + "0 11 42", + "42 0 7", + "57 7 4", + "water-to-light map:", + "88 18 7", + "18 25 70", + "light-to-temperature map:", + "45 77 23", + "81 45 19", + "68 64 13", + "temperature-to-humidity map:", + "0 69 1", + "1 0 69", + "humidity-to-location map:", + "60 56 37", + "56 93 4", + ]; + public static readonly IEnumerable TestAlmanacData = new List { diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs index f121d98..e6691ab 100644 --- a/05/IYGASAF/Program.cs +++ b/05/IYGASAF/Program.cs @@ -18,7 +18,13 @@ public class Program var input = await File.ReadAllLinesAsync(args[0]); - var result = Almanac.Parse(input).GetLowestSeedLocation(); + var seedsAreRanges = args.Length > 1 && args[1] == "part2"; + + Console.WriteLine("Parsing almanac..."); + var almanac = Almanac.Parse(input); + + Console.WriteLine("Getting lowest seed location..."); + var result = almanac.GetLowestSeedLocation(seedsAreRanges); Console.WriteLine($"The lowest seed location is {result}."); @@ -28,31 +34,99 @@ public class Program public class Almanac( List seeds, + List seedRanges, List maps ) { + public List SeedRanges { get; init; } = seedRanges; public List Seeds { get; init; } = seeds; public List Maps { get; init; } = maps; + private static List GetSeedsFromString(string seedsString) => + seedsString + .Split( + ' ', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ) + .Select(long.Parse) + .ToList(); + public long GetSeedLocation(long seed) => Maps.Aggregate( seed, (currentSeed, map) => map.ConvertSourceToDestination(currentSeed) ); - public long GetLowestSeedLocation() => Seeds - .Select(GetSeedLocation) - .Min(); + public class LocationResult + { + public long Value { get; set; } = long.MaxValue; + } + + public long GetLowestSeedLocation(bool seedsAreRanges = false) + { + var lowestLocation = new LocationResult(); + + if (seedsAreRanges) + { + Parallel.ForEach(SeedRanges, (currentSeedRange) => + { + var currentSeedRangeStart = currentSeedRange.Start; + var currentSeedRangeEnd = currentSeedRange.End; + + for (long j = currentSeedRangeStart; j <= currentSeedRangeEnd; j++) + { + var currentSeed = j; + var currentSeedLocation = GetSeedLocation(currentSeed); + + lock (lowestLocation) + { + if (currentSeedLocation < lowestLocation.Value) + { + lowestLocation.Value = currentSeedLocation; + } + } + } + }); + } + else + { + for (int i = 0; i < Seeds.Count; i++) + { + var currentSeed = Seeds[i]; + var currentSeedLocation = GetSeedLocation(currentSeed); + + if (currentSeedLocation < lowestLocation.Value) + { + lowestLocation.Value = currentSeedLocation; + } + } + } + + File.WriteAllText("output.txt", lowestLocation.Value.ToString()); + + return lowestLocation.Value; + } + + public static List ParseSeedsAsRanges(string seedsString) + { + var seeds = new List(); + var seedNumbers = GetSeedsFromString(seedsString); + + for (int i = 0; i < seedNumbers.Count; i += 2) + { + var start = seedNumbers[i]; + var length = seedNumbers[i + 1]; + + seeds.Add(new(start, length)); + } + + return seeds; + } public static Almanac Parse(string[] almanac) { var seedsString = almanac[0].Split(':')[1]; - var seeds = seedsString - .Split( - ' ', - StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries - ) - .Select(long.Parse) - .ToList(); + var seeds = GetSeedsFromString(seedsString); + var seedRanges = ParseSeedsAsRanges(seedsString); var maps = new List(); var ranges = new List(); @@ -86,6 +160,7 @@ public class Almanac( return new Almanac( seeds, + seedRanges, maps ); } @@ -95,7 +170,7 @@ public class Map( List ranges ) { - public List Ranges { get; init; } = ranges; + public List Ranges { get; init; } = [.. ranges.OrderBy(range => range.SourceStart)]; public static Map Parse(string[] ranges) => new( @@ -124,6 +199,16 @@ public class Map( } } +public class SeedRange( + long start, + long length +) +{ + public long Start { get; init; } = start; + public long Length { get; init; } = length; + public long End => Start + Length - 1; +} + public class Range( long rangeLength, long sourceStart, From 79726bc978d3aabecaf4421afe46c650cf2721d1 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:42:07 -0600 Subject: [PATCH 5/7] docs: add xml comments --- 04/Scratchcards.Tests/GlobalUsings.cs | 2 +- 05/IYGASAF.Tests/GlobalUsings.cs | 3 +- 05/IYGASAF/Program.cs | 114 +++++++++++++++++++++++++- README.md | 2 +- 4 files changed, 115 insertions(+), 6 deletions(-) diff --git a/04/Scratchcards.Tests/GlobalUsings.cs b/04/Scratchcards.Tests/GlobalUsings.cs index 2d5b473..d6f0167 100644 --- a/04/Scratchcards.Tests/GlobalUsings.cs +++ b/04/Scratchcards.Tests/GlobalUsings.cs @@ -1,3 +1,3 @@ global using FluentAssertions; -global using Xunit; +global using Xunit; \ No newline at end of file diff --git a/05/IYGASAF.Tests/GlobalUsings.cs b/05/IYGASAF.Tests/GlobalUsings.cs index 7fef4b0..2d5b473 100644 --- a/05/IYGASAF.Tests/GlobalUsings.cs +++ b/05/IYGASAF.Tests/GlobalUsings.cs @@ -1,2 +1,3 @@ +global using FluentAssertions; + global using Xunit; -global using FluentAssertions; \ No newline at end of file diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs index e6691ab..de90804 100644 --- a/05/IYGASAF/Program.cs +++ b/05/IYGASAF/Program.cs @@ -32,14 +32,32 @@ public class Program } } +/// +/// Represents an almanac. +/// +/// The seeds. +/// The seed ranges. +/// The maps. +/// An instance of . public class Almanac( List seeds, List seedRanges, List maps ) { + /// + /// Gets the seed ranges. + /// public List SeedRanges { get; init; } = seedRanges; + + /// + /// Gets the seeds. + /// public List Seeds { get; init; } = seeds; + + /// + /// Gets the maps. + /// public List Maps { get; init; } = maps; private static List GetSeedsFromString(string seedsString) => @@ -51,16 +69,26 @@ public class Almanac( .Select(long.Parse) .ToList(); + /// + /// Gets the seed location. + /// + /// The seed. + /// The seed location. public long GetSeedLocation(long seed) => Maps.Aggregate( seed, (currentSeed, map) => map.ConvertSourceToDestination(currentSeed) ); - public class LocationResult + private class LocationResult { public long Value { get; set; } = long.MaxValue; } + /// + /// Gets the lowest seed location. + /// + /// If set to true seeds are treated as ranges + /// The lowest seed location. public long GetLowestSeedLocation(bool seedsAreRanges = false) { var lowestLocation = new LocationResult(); @@ -101,11 +129,14 @@ public class Almanac( } } - File.WriteAllText("output.txt", lowestLocation.Value.ToString()); - return lowestLocation.Value; } + /// + /// Parses the seeds as ranges. + /// + /// The seeds string. + /// The seeds as ranges. public static List ParseSeedsAsRanges(string seedsString) { var seeds = new List(); @@ -122,6 +153,11 @@ public class Almanac( return seeds; } + /// + /// Parses the specified almanac. + /// + /// The almanac. + /// An instance of . public static Almanac Parse(string[] almanac) { var seedsString = almanac[0].Split(':')[1]; @@ -166,22 +202,45 @@ public class Almanac( } } +/// +/// Represents a map. +/// +/// The ranges contained within the map +/// An instance of . public class Map( List ranges ) { + /// + /// Gets the ranges. + /// public List Ranges { get; init; } = [.. ranges.OrderBy(range => range.SourceStart)]; + /// + /// Parses a map from the specified ranges. + /// + /// The ranges. + /// An instance of . public static Map Parse(string[] ranges) => new( ranges.Select(Range.Parse).ToList() ); + /// + /// Gets the source range. + /// + /// The source value. + /// The source . public Range? GetSourceRange(long sourceValue) => Ranges .Where(range => range.SourceStart <= sourceValue && range.SourceEnd >= sourceValue) .FirstOrDefault(); + /// + /// Converts the source to destination. + /// + /// The value to convert. + /// The converted value. public long ConvertSourceToDestination(long valueToConvert) { var sourceRange = GetSourceRange(valueToConvert); @@ -199,28 +258,77 @@ public class Map( } } +/// +/// Represents a seed range. +/// +/// The start. +/// The length. +/// An instance of . public class SeedRange( long start, long length ) { + /// + /// Gets the start of the range. It is inclusive. + /// public long Start { get; init; } = start; + + /// + /// Gets the length of the range. + /// public long Length { get; init; } = length; + + /// + /// Gets the end of the range. It is inclusive. + /// public long End => Start + Length - 1; } +/// +/// Represents a map range. +/// +/// Length of the range. +/// The source start. +/// The destination start. +/// An instance of . public class Range( long rangeLength, long sourceStart, long destinationStart ) { + /// + /// Gets the length of the range. + /// public long RangeLength { get; init; } = rangeLength; + + /// + /// Gets the start of the source range. It is inclusive. + /// public long SourceStart { get; init; } = sourceStart; + + /// + /// Gets the end of the source range. It is inclusive. + /// public long SourceEnd => SourceStart + RangeLength - 1; + + /// + /// Gets the start of the destination range. It is inclusive. + /// public long DestinationStart { get; init; } = destinationStart; + + /// + /// Gets the end of the destination range. It is inclusive. + /// public long DestinationEnd => DestinationStart + RangeLength - 1; + /// + /// Parses the specified range. + /// + /// The range. + /// An instance of . + /// Range must be in the format of 'DestinationRangeStart:long SourceRangeStart:long RangeLength:long' public static Range Parse(string range) { var parts = range.Split( diff --git a/README.md b/README.md index ce7b631..3d3486a 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ dotnet run -- part2 | 02 | [Problem](./02/PROBLEM.md) | [Solution](./02/CubeConundrum/) | ✅ | The key to me here was to parse the input into a useful model. | | 03 | [Problem](./03/PROBLEM.md) | [Solution](./03/GearRatios/) | ✅ | The edge case that got me here was lines ending with a part number. | | 04 | [Problem](./04/PROBLEM.md) | [Solution](./04/Scratchcards/) | ✅ | Part 2 gets out of hand quickly with just 200 cards. | -| 05 | [Problem](./05/PROBLEM.md) | [Solution](./05/) | ⌛ | +| 05 | [Problem](./05/PROBLEM.md) | [Solution](./05/) | ✅ | I brute forced part 2 using parallelism. I know shame. | | 06 | [Problem](./06/PROBLEM.md) | [Solution](./06/) | ⌛ | | 07 | [Problem](./07/PROBLEM.md) | [Solution](./07/) | ⌛ | | 08 | [Problem](./08/PROBLEM.md) | [Solution](./08/) | ⌛ | From 5f944717972b5b94a3e76d817d0ad9155e21754c Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:45:12 -0600 Subject: [PATCH 6/7] chore: add timer --- 05/IYGASAF/Program.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/05/IYGASAF/Program.cs b/05/IYGASAF/Program.cs index de90804..bacb027 100644 --- a/05/IYGASAF/Program.cs +++ b/05/IYGASAF/Program.cs @@ -1,4 +1,6 @@ -namespace IYGASAF; +using System.Diagnostics; + +namespace IYGASAF; public class Program { @@ -24,9 +26,14 @@ public class Program var almanac = Almanac.Parse(input); Console.WriteLine("Getting lowest seed location..."); - var result = almanac.GetLowestSeedLocation(seedsAreRanges); - Console.WriteLine($"The lowest seed location is {result}."); + var stopwatch = new Stopwatch(); + stopwatch.Start(); + var result = almanac.GetLowestSeedLocation(seedsAreRanges); + stopwatch.Stop(); + + + Console.WriteLine($"The lowest seed location is {result}. ({stopwatch.ElapsedMilliseconds}ms)"); return (int)result; } From f6643bf292f081503b83a81c4a5824cef544f829 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:46:47 -0600 Subject: [PATCH 7/7] docs: update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d3486a..4ce98e9 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ dotnet run -- part2 | 02 | [Problem](./02/PROBLEM.md) | [Solution](./02/CubeConundrum/) | ✅ | The key to me here was to parse the input into a useful model. | | 03 | [Problem](./03/PROBLEM.md) | [Solution](./03/GearRatios/) | ✅ | The edge case that got me here was lines ending with a part number. | | 04 | [Problem](./04/PROBLEM.md) | [Solution](./04/Scratchcards/) | ✅ | Part 2 gets out of hand quickly with just 200 cards. | -| 05 | [Problem](./05/PROBLEM.md) | [Solution](./05/) | ✅ | I brute forced part 2 using parallelism. I know shame. | +| 05 | [Problem](./05/PROBLEM.md) | [Solution](./05/IYGASAF/) | ✅ | I brute forced part 2 using parallelism. I know shame. | | 06 | [Problem](./06/PROBLEM.md) | [Solution](./06/) | ⌛ | | 07 | [Problem](./07/PROBLEM.md) | [Solution](./07/) | ⌛ | | 08 | [Problem](./08/PROBLEM.md) | [Solution](./08/) | ⌛ |