Merge pull request #4 from StevanFreeborn/stevanfreeborn/feat/solve-puzzle-4

feat: solve puzzle 4
This commit is contained in:
Stevan Freeborn
2023-12-04 13:29:54 -06:00
committed by GitHub
11 changed files with 428 additions and 2 deletions
@@ -27,4 +27,10 @@
<ProjectReference Include="..\GearRatios\GearRatios.csproj" /> <ProjectReference Include="..\GearRatios\GearRatios.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Include="..\INPUT.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>
+12
View File
@@ -36,6 +36,8 @@ public class PuzzleSolverTests
".664.598..", ".664.598..",
]; ];
private static readonly string[] Input = File.ReadAllLines("INPUT.txt");
public static IEnumerable<object[]> SumGearRatios => public static IEnumerable<object[]> SumGearRatios =>
new List<object[]> new List<object[]>
{ {
@@ -44,6 +46,11 @@ public class PuzzleSolverTests
TestSchematic, TestSchematic,
467835, 467835,
}, },
new object[]
{
Input,
81997870,
}
}; };
public static IEnumerable<object?[]> SumPartNumbersData => public static IEnumerable<object?[]> SumPartNumbersData =>
@@ -84,6 +91,11 @@ public class PuzzleSolverTests
"........375...%.........*......450.456.$.........714........851.327..#...+......*...+.......179.630....854.................................*", "........375...%.........*......450.456.$.........714........851.327..#...+......*...+.......179.630....854.................................*",
}, },
11612 11612
},
new object[]
{
Input,
550934,
} }
}; };
} }
+105
View File
@@ -0,0 +1,105 @@
namespace Scratchcards.Tests;
public class CardTests
{
[Theory]
[MemberData(nameof(TestData.ParseCardData), MemberType = typeof(TestData))]
public void Parse_GivenInput_ItShouldReturnExpectedCard(string input, Card expected)
{
var result = Card.Parse(input);
result.Should().BeEquivalentTo(expected);
}
[Theory]
[MemberData(nameof(TestData.GetCardValueData), MemberType = typeof(TestData))]
public void GetCardValue_GivenCard_ItShouldReturnExpectedValue(Card card, int expected)
{
var result = card.GetCardValue();
result.Should().Be(expected);
}
public static class TestData
{
private static readonly Dictionary<string, Card> TestCards =
new()
{
{
"Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53",
new Card(
1,
[41, 48, 83, 86, 17],
[83, 86, 6, 31, 17, 9, 48, 53]
)
},
{
"Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19",
new Card(
2,
[13, 32, 20, 16, 61],
[61, 30, 68, 82, 17, 32, 24, 19]
)
},
{
"Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1",
new Card(
3,
[1, 21, 53, 59, 44],
[69, 82, 63, 72, 16, 21, 14, 1]
)
},
{
"Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83",
new Card(
4,
[41, 92, 73, 84, 69],
[59, 84, 76, 51, 58, 5, 54, 83]
)
},
{
"Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36",
new Card(
5,
[87, 83, 26, 28, 32],
[88, 30, 70, 12, 93, 22, 82, 36]
)
},
{
"Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11",
new Card(
6,
[31, 18, 13, 56, 72],
[74, 77, 10, 23, 35, 67, 36, 11]
)
},
};
public static IEnumerable<object[]> ParseCardData =>
TestCards
.Select(kvp => new object[] { kvp.Key, kvp.Value })
.ToList();
public static IEnumerable<object[]> GetCardValueData()
{
for (var i = 0; i < TestCards.Count; i++)
{
var currentCard = TestCards.ElementAt(i);
var expectedValue = i switch
{
0 => 8,
1 => 2,
2 => 2,
3 => 1,
4 => 0,
5 => 0,
_ => throw new Exception("Unexpected card index"),
};
yield return new object[]
{
currentCard.Value,
expectedValue
};
}
}
}
}
+3
View File
@@ -0,0 +1,3 @@
global using FluentAssertions;
global using Xunit;
@@ -0,0 +1,67 @@
namespace Scratchcards.Tests;
public class PuzzleSolverTests
{
private readonly PuzzleSolver _sut = new();
[Theory]
[MemberData(nameof(TestData.SumCardValuesData), MemberType = typeof(TestData))]
public void SumCardValues_GivenCards_ItShouldReturnExpectedValue(string[] cards, int expected)
{
var result = _sut.SumCardValues(cards);
result.Should().Be(expected);
}
[Theory]
[MemberData(nameof(TestData.GetTotalCardCountData), MemberType = typeof(TestData))]
public void GetTotalCardCount_GivenCards_ItShouldReturnExpectedValue(string[] cards, int expected)
{
var result = _sut.GetTotalCardCount(cards);
result.Should().Be(expected);
}
public static class TestData
{
private static readonly string[] ExampleInput =
[
"Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53",
"Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19",
"Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1",
"Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83",
"Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36",
"Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11",
];
private static string[] Input => File.ReadAllLines("INPUT.txt");
public static IEnumerable<object[]> GetTotalCardCountData =>
new List<object[]>
{
new object[]
{
ExampleInput,
30,
},
new object[]
{
Input,
5920640,
},
};
public static IEnumerable<object[]> SumCardValuesData =>
new List<object[]>
{
new object[]
{
ExampleInput,
13,
},
new object[]
{
Input,
23235,
},
};
}
}
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Scratchcards\Scratchcards.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="..\INPUT.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
+171
View File
@@ -0,0 +1,171 @@
namespace Scratchcards;
public class Program
{
public static async 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;
}
var puzzleSolver = new PuzzleSolver();
var input = await File.ReadAllLinesAsync(args[0]);
var result = args.Length is 2 && args[1] == "part2"
? puzzleSolver.GetTotalCardCount(input)
: puzzleSolver.SumCardValues(input);
if (args.Length is 2 && args[1] == "part2")
{
Console.WriteLine($"The total number of cards is {result}.");
}
else
{
Console.WriteLine($"The total value of the cards is {result}.");
}
return result;
}
}
/// <summary>
/// Solves the puzzle.
/// </summary>
public class PuzzleSolver
{
/// <summary>
/// Sums the value of the cards.
/// </summary>
/// <param name="cards">The cards.</param>
/// <returns>The sum of the cards.</returns>
public int SumCardValues(string[] cards) => cards
.Select(Card.Parse)
.Sum(c => c.GetCardValue());
/// <summary>
/// Gets the total number of cards.
/// </summary>
/// <param name="cards">The cards.</param>
/// <returns>The total number of cards.</returns>
public int GetTotalCardCount(string[] cards)
{
var cardStringsToProcess = new List<string>(cards);
for (var i = 0; i < cardStringsToProcess.Count; i++)
{
var currentCardString = cardStringsToProcess[i];
var currentCardStringIndex = Array.IndexOf(cards, currentCardString);
var currentCard = Card.Parse(currentCardString);
var numOfMatchingNumbersForCurrentCard = currentCard.MatchingNumbers.Count;
var cardIndexesToCopy = Enumerable.Range(
currentCardStringIndex + 1,
Math.Min(
numOfMatchingNumbersForCurrentCard,
cards.Length - currentCardStringIndex - 1
)
);
foreach (var index in cardIndexesToCopy)
{
cardStringsToProcess.Add(cards[index]);
}
}
return cardStringsToProcess.Count;
}
}
/// <summary>
/// Represents a card.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="winningNumbers">The winning numbers.</param>
/// <param name="numbers">The numbers.</param>
/// <returns>An instance of <see cref="Card"/>.</returns>
public class Card(
int id,
List<int> winningNumbers,
List<int> numbers
)
{
/// <summary>
/// Gets the identifier.
/// </summary>
public int Id { get; init; } = id;
/// <summary>
/// Gets the winning numbers.
/// </summary>
public List<int> WinningNumbers { get; init; } = winningNumbers;
/// <summary>
/// Gets the numbers.
/// </summary>
public List<int> Numbers { get; init; } = numbers;
/// <summary>
/// Gets the matching numbers.
/// </summary>
public List<int> MatchingNumbers => Numbers.Intersect(WinningNumbers).ToList();
/// <summary>
/// Gets the value of the card.
/// </summary>
/// <returns>The value of the card.</returns>
public int GetCardValue() => MatchingNumbers.Count is 1
? 1
: (int)Math.Pow(2, MatchingNumbers.Count - 1);
/// <summary>
/// Parses the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>An instance of <see cref="Card"/>.</returns>
public static Card Parse(string input)
{
var parts = input.Split(':');
var cardId = int.Parse(
parts[0].Split(
' ',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
)[1]
);
var numberStrings = parts[1].Trim();
var numberParts = numberStrings
.Split('|')
.Select(s => s.Trim())
.ToArray();
var winningNumbersString = numberParts[0];
var numbersString = numberParts[1];
var winningNumbers = winningNumbersString
.Split(
' ',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
)
.Select(s => s.Trim())
.Select(int.Parse)
.ToList();
var numbers = numbersString
.Split(
' ',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
)
.Select(s => s.Trim())
.Select(int.Parse)
.ToList();
return new Card(cardId, winningNumbers, numbers);
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+16
View File
@@ -21,6 +21,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GearRatios", "03\GearRatios
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GearRatios.Tests", "03\GearRatios.Tests\GearRatios.Tests.csproj", "{FEE9253C-A56B-4735-BDB3-C62220C5B1B1}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GearRatios.Tests", "03\GearRatios.Tests\GearRatios.Tests.csproj", "{FEE9253C-A56B-4735-BDB3-C62220C5B1B1}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "04", "04", "{522D6D1E-54AD-4479-BB78-0AB5D7493EFC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scratchcards", "04\Scratchcards\Scratchcards.csproj", "{B58CF14B-97A1-45F6-967F-29FA82DAFD0F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scratchcards.Tests", "04\Scratchcards.Tests\Scratchcards.Tests.csproj", "{FF8A5512-85FD-45E7-9F97-EC528465949C}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -54,6 +60,14 @@ Global
{FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Release|Any CPU.Build.0 = Release|Any CPU {FEE9253C-A56B-4735-BDB3-C62220C5B1B1}.Release|Any CPU.Build.0 = Release|Any CPU
{B58CF14B-97A1-45F6-967F-29FA82DAFD0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B58CF14B-97A1-45F6-967F-29FA82DAFD0F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B58CF14B-97A1-45F6-967F-29FA82DAFD0F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B58CF14B-97A1-45F6-967F-29FA82DAFD0F}.Release|Any CPU.Build.0 = Release|Any CPU
{FF8A5512-85FD-45E7-9F97-EC528465949C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{3F8EAC09-4BC7-43AA-B72B-48DDD2710F6D} = {8C29858C-623A-461A-BF0B-254E151CD9C2} {3F8EAC09-4BC7-43AA-B72B-48DDD2710F6D} = {8C29858C-623A-461A-BF0B-254E151CD9C2}
@@ -62,5 +76,7 @@ Global
{4825CE42-4717-4DA6-944F-9BD9A825932B} = {4FD81B09-302F-4C76-BECB-B4559DF3984F} {4825CE42-4717-4DA6-944F-9BD9A825932B} = {4FD81B09-302F-4C76-BECB-B4559DF3984F}
{F697AC19-C92D-4E2A-975A-1A16A1961133} = {EA04152D-316A-4AA4-9BC1-57F6A9F3CD4E} {F697AC19-C92D-4E2A-975A-1A16A1961133} = {EA04152D-316A-4AA4-9BC1-57F6A9F3CD4E}
{FEE9253C-A56B-4735-BDB3-C62220C5B1B1} = {EA04152D-316A-4AA4-9BC1-57F6A9F3CD4E} {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}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
+1 -1
View File
@@ -40,7 +40,7 @@ dotnet run -- <path-to-input-file> part2
| 01 | [Problem](./01/PROBLEM.md) | [Solution](./01/Trebuchet/) | ✅ | The trickiest part here was accounting for overlapping digit words. | | 01 | [Problem](./01/PROBLEM.md) | [Solution](./01/Trebuchet/) | ✅ | The trickiest part here was accounting for overlapping digit words. |
| 02 | [Problem](./02/PROBLEM.md) | [Solution](./02/CubeConundrum/) | ✅ | The key to me here was to parse the input into a useful model. | | 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. | | 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/) | | | 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/) | ⌛ |
| 06 | [Problem](./06/PROBLEM.md) | [Solution](./06/) | ⌛ | | 06 | [Problem](./06/PROBLEM.md) | [Solution](./06/) | ⌛ |
| 07 | [Problem](./07/PROBLEM.md) | [Solution](./07/) | ⌛ | | 07 | [Problem](./07/PROBLEM.md) | [Solution](./07/) | ⌛ |