Compare commits

1 Commits

Author SHA1 Message Date
68a494c929 WIP AdventOfCode 2023 Day24 Part2 2023-12-25 05:13:36 +01:00
113 changed files with 1305 additions and 3701 deletions

View File

@@ -1,9 +1,10 @@
[*] [*]
# Microsoft .NET properties # Microsoft .NET properties
csharp_indent_braces = false csharp_indent_braces = false
csharp_new_line_before_members_in_object_initializers = false csharp_new_line_before_members_in_object_initializers = false
csharp_new_line_before_open_brace = accessors, anonymous_methods, control_blocks, events, indexers, lambdas, local_functions, methods, properties, types csharp_new_line_before_open_brace = accessors,anonymous_methods,control_blocks,events,indexers,lambdas,local_functions,methods,properties,types
csharp_preferred_modifier_order = private, public, protected, internal, file, new, readonly, abstract, virtual, sealed, static, override, extern, unsafe, volatile, async, required:suggestion csharp_preferred_modifier_order = private, public, protected, internal, file, new, readonly, abstract, virtual, sealed, static, override, extern, unsafe, volatile, async, required:suggestion
csharp_prefer_braces = true:none csharp_prefer_braces = true:none
csharp_preserve_single_line_blocks = true csharp_preserve_single_line_blocks = true

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeveloperToolsToolWindowSettingsV1" lastSelectedContentNodeId="base64-encoder-decoder">
<developerToolsConfigurations />
</component>
</project>

View File

@@ -1,3 +0,0 @@
<component name="ProjectDictionaryState">
<dictionary name="var" />
</component>

View File

@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode.Common</RootNamespace> <RootNamespace>AdventOfCode.Common</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@@ -15,7 +15,7 @@ public static class DayHelper
return null; return null;
} }
private static void RunDay(string eventName, int dayNumber) public static void RunDay(string eventName, int dayNumber)
{ {
Console.WriteLine($"Day {dayNumber:00}"); Console.WriteLine($"Day {dayNumber:00}");
Console.WriteLine("------"); Console.WriteLine("------");
@@ -64,7 +64,7 @@ public static class DayHelper
} }
} }
private static void RunDay(string eventName) public static void RunDay(string eventName)
{ {
for (int currentDay = 1; currentDay < 25; currentDay++) for (int currentDay = 1; currentDay < 25; currentDay++)
{ {

73
AdventOfCode.sln Normal file
View File

@@ -0,0 +1,73 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30711.63
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdventOfCode2020", "AdventOfCode2020\AdventOfCode2020.csproj", "{CD1829F6-166D-4F78-AB95-C58916F42494}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2020.Tests", "AdventOfCode2020.Tests\AdventOfCode2020.Tests.csproj", "{2B079D7D-08D4-4FFB-A000-858FFDD945FA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2017", "AdventOfCode2017\AdventOfCode2017.csproj", "{49C8A67C-D94C-4CFB-B7FB-C19A1A83CA66}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2017.Tests", "AdventOfCode2017.Tests\AdventOfCode2017.Tests.csproj", "{3537CE59-1C57-481B-85F7-3F2A1F0EDE1D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2018", "AdventOfCode2018\AdventOfCode2018.csproj", "{43DAF84F-369A-48C5-9292-536094336F8F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2018.Tests", "AdventOfCode2018.Tests\AdventOfCode2018.Tests.csproj", "{EE35694D-97C1-485D-9FFE-73912FA97446}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2023", "AdventOfCode2023\AdventOfCode2023.csproj", "{0D90084C-D2D9-489E-BFC3-5E63AE9947B3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode2023.Tests", "AdventOfCode2023.Tests\AdventOfCode2023.Tests.csproj", "{00869F26-F53E-451D-BEA2-4E3FFE2216FB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdventOfCode.Common", "AdventOfCode.Common\AdventOfCode.Common.csproj", "{D6C2B27F-22C3-49E2-9591-225B7132452D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CD1829F6-166D-4F78-AB95-C58916F42494}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD1829F6-166D-4F78-AB95-C58916F42494}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD1829F6-166D-4F78-AB95-C58916F42494}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD1829F6-166D-4F78-AB95-C58916F42494}.Release|Any CPU.Build.0 = Release|Any CPU
{2B079D7D-08D4-4FFB-A000-858FFDD945FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B079D7D-08D4-4FFB-A000-858FFDD945FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B079D7D-08D4-4FFB-A000-858FFDD945FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B079D7D-08D4-4FFB-A000-858FFDD945FA}.Release|Any CPU.Build.0 = Release|Any CPU
{49C8A67C-D94C-4CFB-B7FB-C19A1A83CA66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49C8A67C-D94C-4CFB-B7FB-C19A1A83CA66}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49C8A67C-D94C-4CFB-B7FB-C19A1A83CA66}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49C8A67C-D94C-4CFB-B7FB-C19A1A83CA66}.Release|Any CPU.Build.0 = Release|Any CPU
{3537CE59-1C57-481B-85F7-3F2A1F0EDE1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3537CE59-1C57-481B-85F7-3F2A1F0EDE1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3537CE59-1C57-481B-85F7-3F2A1F0EDE1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3537CE59-1C57-481B-85F7-3F2A1F0EDE1D}.Release|Any CPU.Build.0 = Release|Any CPU
{43DAF84F-369A-48C5-9292-536094336F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43DAF84F-369A-48C5-9292-536094336F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43DAF84F-369A-48C5-9292-536094336F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43DAF84F-369A-48C5-9292-536094336F8F}.Release|Any CPU.Build.0 = Release|Any CPU
{EE35694D-97C1-485D-9FFE-73912FA97446}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE35694D-97C1-485D-9FFE-73912FA97446}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE35694D-97C1-485D-9FFE-73912FA97446}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE35694D-97C1-485D-9FFE-73912FA97446}.Release|Any CPU.Build.0 = Release|Any CPU
{0D90084C-D2D9-489E-BFC3-5E63AE9947B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0D90084C-D2D9-489E-BFC3-5E63AE9947B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D90084C-D2D9-489E-BFC3-5E63AE9947B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D90084C-D2D9-489E-BFC3-5E63AE9947B3}.Release|Any CPU.Build.0 = Release|Any CPU
{00869F26-F53E-451D-BEA2-4E3FFE2216FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00869F26-F53E-451D-BEA2-4E3FFE2216FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00869F26-F53E-451D-BEA2-4E3FFE2216FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00869F26-F53E-451D-BEA2-4E3FFE2216FB}.Release|Any CPU.Build.0 = Release|Any CPU
{D6C2B27F-22C3-49E2-9591-225B7132452D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6C2B27F-22C3-49E2-9591-225B7132452D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6C2B27F-22C3-49E2-9591-225B7132452D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6C2B27F-22C3-49E2-9591-225B7132452D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4BAE59D7-7AFF-42B6-A391-CD22CD443B03}
EndGlobalSection
EndGlobal

View File

@@ -6,12 +6,9 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=VY/@EntryIndexedValue">VY</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=VY/@EntryIndexedValue">VY</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Locals/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb_AaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Locals/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=61a991a4_002Dd0a3_002D4d19_002D90a5_002Df8f4d75c30c1/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Local variables"&gt;&lt;ElementKinds&gt;&lt;Kind Name="LOCAL_VARIABLE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a0b4bc4d_002Dd13b_002D4a37_002Db37e_002Dc9c6864e4302/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="NAMESPACE" /&gt;&lt;Kind Name="CLASS" /&gt;&lt;Kind Name="STRUCT" /&gt;&lt;Kind Name="ENUM" /&gt;&lt;Kind Name="DELEGATE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=AdventOfCode_002A_002ETests_003B_002A_003B_002A_003B_002A/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=AdventOfCode_002A_002ETests_003B_002A_003B_002A_003B_002A/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=AdventOfCode_002ECommon_003B_002A_003B_002A_003B_002A/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=AdventOfCode_002ECommon_003B_002A_003B_002A_003B_002A/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=_002A_003B_002A_003BProgram_003B_002A/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=_002A_003B_002A_003BProgram_003B_002A/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Chrono/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Chrono/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Extrapolator/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Extrapolator/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=extrapolators/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary> <s:Boolean x:Key="/Default/UserDictionary/Words/=extrapolators/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -1,13 +0,0 @@
<Solution>
<Project Path="AdventOfCode.Common\AdventOfCode.Common.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2017.Tests\AdventOfCode2017.Tests.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2017\AdventOfCode2017.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2018.Tests\AdventOfCode2018.Tests.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2018\AdventOfCode2018.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2020.Tests\AdventOfCode2020.Tests.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2020\AdventOfCode2020.csproj"/>
<Project Path="AdventOfCode2023.Tests\AdventOfCode2023.Tests.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2023\AdventOfCode2023.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2024.Tests\AdventOfCode2024.Tests.csproj" Type="Classic C#"/>
<Project Path="AdventOfCode2024\AdventOfCode2024.csproj" Type="Classic C#"/>
</Solution>

View File

@@ -1,18 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2017.Tests</RootNamespace> <RootNamespace>AdventOfCode2017.Tests</RootNamespace>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.3"/> <PackageReference Include="xunit" Version="2.6.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.5"> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -20,7 +18,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode2017\AdventOfCode2017.csproj"/> <ProjectReference Include="..\AdventOfCode2017\AdventOfCode2017.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -9,7 +9,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["1122"]); string result = day01.ResolvePart1(new[] { "1122", });
Assert.Equal("3", result); Assert.Equal("3", result);
} }
@@ -19,7 +19,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["1111"]); string result = day01.ResolvePart1(new[] { "1111", });
Assert.Equal("4", result); Assert.Equal("4", result);
} }
@@ -29,7 +29,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["1234"]); string result = day01.ResolvePart1(new[] { "1234", });
Assert.Equal("0", result); Assert.Equal("0", result);
} }
@@ -39,7 +39,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["91212129"]); string result = day01.ResolvePart1(new[] { "91212129", });
Assert.Equal("9", result); Assert.Equal("9", result);
} }
@@ -53,7 +53,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["1212"]); string result = day01.ResolvePart2(new[] { "1212", });
Assert.Equal("6", result); Assert.Equal("6", result);
} }
@@ -63,7 +63,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["1221"]); string result = day01.ResolvePart2(new[] { "1221", });
Assert.Equal("0", result); Assert.Equal("0", result);
} }
@@ -73,7 +73,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["123425"]); string result = day01.ResolvePart2(new[] { "123425", });
Assert.Equal("4", result); Assert.Equal("4", result);
} }
@@ -83,7 +83,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["123123"]); string result = day01.ResolvePart2(new[] { "123123", });
Assert.Equal("12", result); Assert.Equal("12", result);
} }
@@ -93,7 +93,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["12131415"]); string result = day01.ResolvePart2(new[] { "12131415", });
Assert.Equal("4", result); Assert.Equal("4", result);
} }

View File

@@ -7,11 +7,11 @@ public class Day02_Tests
{ {
Day02 day02 = new(); Day02 day02 = new();
string result = day02.ResolvePart1([ string result = day02.ResolvePart1(new[] {
"5 1 9 5", "5 1 9 5",
"7 5 3", "7 5 3",
"2 4 6 8", "2 4 6 8",
]); });
Assert.Equal("18", result); Assert.Equal("18", result);
} }
@@ -21,11 +21,11 @@ public class Day02_Tests
{ {
Day02 day02 = new(); Day02 day02 = new();
string result = day02.ResolvePart2([ string result = day02.ResolvePart2(new[] {
"5 9 2 8", "5 9 2 8",
"9 4 7 3", "9 4 7 3",
"3 8 6 5", "3 8 6 5",
]); });
Assert.Equal("9", result); Assert.Equal("9", result);
} }

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MSTest.TestAdapter" version="1.3.2" targetFramework="net461" />
<package id="MSTest.TestFramework" version="1.3.2" targetFramework="net461" />
</packages>

View File

@@ -2,9 +2,8 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2017</RootNamespace> <RootNamespace>AdventOfCode2017</RootNamespace>
</PropertyGroup> </PropertyGroup>
@@ -15,7 +14,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj"/> <ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -48,10 +48,10 @@ public class Day01 : IDay
{ {
string input = inputs[0]; string input = inputs[0];
int value = 0; int value = 0;
for (int i = 0; i < input.Length; i++) for(int i = 0; i < input.Length; i++)
{ {
int nextI = (i + 1) % input.Length; int nextI = (i + 1) % input.Length;
if (input[i] == input[nextI]) if(input[i] == input[nextI])
{ {
value += (input[i] - '0'); value += (input[i] - '0');
} }

View File

@@ -51,10 +51,10 @@ public class Day02 : IDay
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
int checksum = 0; int checksum = 0;
foreach (string input in inputs) foreach(string input in inputs)
{ {
int[] row = input int[] row = input
.Split([" ", " "], StringSplitOptions.RemoveEmptyEntries) .Split(new[] { " ", " " }, StringSplitOptions.RemoveEmptyEntries)
.Select(cell => Convert.ToInt32(cell)) .Select(cell => Convert.ToInt32(cell))
.ToArray(); .ToArray();
int max = row.Max(); int max = row.Max();
@@ -70,7 +70,7 @@ public class Day02 : IDay
foreach (string input in inputs) foreach (string input in inputs)
{ {
int[] row = input int[] row = input
.Split([" ", " "], StringSplitOptions.RemoveEmptyEntries) .Split(new[] { " ", " " }, StringSplitOptions.RemoveEmptyEntries)
.Select(cell => Convert.ToInt32(cell)) .Select(cell => Convert.ToInt32(cell))
.ToArray(); .ToArray();

View File

@@ -30,11 +30,11 @@ public class Day03 : IDay
{ {
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
return string.Empty; return null;
} }
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
return string.Empty; return null;
} }
} }

View File

@@ -1,18 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2018.Tests</RootNamespace> <RootNamespace>AdventOfCode2018.Tests</RootNamespace>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.3"/> <PackageReference Include="xunit" Version="2.6.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.5"> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -20,7 +18,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode2018\AdventOfCode2018.csproj"/> <ProjectReference Include="..\AdventOfCode2018\AdventOfCode2018.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -9,7 +9,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["+1", "-2", "+3", "+1"]); string result = day01.ResolvePart1(new[] { "+1", "-2", "+3", "+1", });
Assert.Equal("3", result); Assert.Equal("3", result);
} }
@@ -19,7 +19,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["+1", "+1", "+1"]); string result = day01.ResolvePart1(new[] { "+1", "+1", "+1", });
Assert.Equal("3", result); Assert.Equal("3", result);
} }
@@ -29,7 +29,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["+1", "+1", "-2"]); string result = day01.ResolvePart1(new[] { "+1", "+1", "-2", });
Assert.Equal("0", result); Assert.Equal("0", result);
} }
@@ -39,7 +39,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart1(["-1", "-2", "-3"]); string result = day01.ResolvePart1(new[] { "-1", "-2", "-3", });
Assert.Equal("-6", result); Assert.Equal("-6", result);
} }
@@ -53,7 +53,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["+1", "-2", "+3", "+1"]); string result = day01.ResolvePart2(new[] { "+1", "-2", "+3", "+1", });
Assert.Equal("2", result); Assert.Equal("2", result);
} }
@@ -63,7 +63,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["+1", "-1"]); string result = day01.ResolvePart2(new[] { "+1", "-1", });
Assert.Equal("0", result); Assert.Equal("0", result);
} }
@@ -73,7 +73,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["+3", "+3", "+4", "-2", "-4"]); string result = day01.ResolvePart2(new[] { "+3", "+3", "+4", "-2", "-4", });
Assert.Equal("10", result); Assert.Equal("10", result);
} }
@@ -83,7 +83,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["-6", "+3", "+8", "+5", "-6"]); string result = day01.ResolvePart2(new[] { "-6", "+3", "+8", "+5", "-6", });
Assert.Equal("5", result); Assert.Equal("5", result);
} }
@@ -93,7 +93,7 @@ public class Day01_Tests
{ {
Day01 day01 = new(); Day01 day01 = new();
string result = day01.ResolvePart2(["+7", "+7", "-2", "-7", "-4"]); string result = day01.ResolvePart2(new[] { "+7", "+7", "-2", "-7", "-4", });
Assert.Equal("14", result); Assert.Equal("14", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day02_Tests
{ {
Day02 day02 = new(); Day02 day02 = new();
string result = day02.ResolvePart1([ string result = day02.ResolvePart1(new[] {
"abcdef", "abcdef",
"bababc", "bababc",
"abbcde", "abbcde",
@@ -15,7 +15,7 @@ public class Day02_Tests
"aabcdd", "aabcdd",
"abcdee", "abcdee",
"ababab", "ababab",
]); });
Assert.Equal("12", result); Assert.Equal("12", result);
} }
@@ -25,7 +25,7 @@ public class Day02_Tests
{ {
Day02 day02 = new(); Day02 day02 = new();
string result = day02.ResolvePart2([ string result = day02.ResolvePart2(new[] {
"abcde", "abcde",
"fghij", "fghij",
"klmno", "klmno",
@@ -33,7 +33,7 @@ public class Day02_Tests
"fguij", "fguij",
"axcye", "axcye",
"wvxyz", "wvxyz",
]); });
Assert.Equal("fgij", result); Assert.Equal("fgij", result);
} }

View File

@@ -96,11 +96,11 @@ public class Day03_Tests
{ {
Day03 day03 = new(); Day03 day03 = new();
string result = day03.ResolvePart1([ string result = day03.ResolvePart1(new[] {
"#1 @ 1,3: 4x4", "#1 @ 1,3: 4x4",
"#2 @ 3,1: 4x4", "#2 @ 3,1: 4x4",
"#3 @ 5,5: 2x2", "#3 @ 5,5: 2x2",
]); });
Assert.Equal("4", result); Assert.Equal("4", result);
} }
@@ -110,11 +110,11 @@ public class Day03_Tests
{ {
Day03 day03 = new(); Day03 day03 = new();
string result = day03.ResolvePart2([ string result = day03.ResolvePart2(new[] {
"#1 @ 1,3: 4x4", "#1 @ 1,3: 4x4",
"#2 @ 3,1: 4x4", "#2 @ 3,1: 4x4",
"#3 @ 5,5: 2x2", "#3 @ 5,5: 2x2",
]); });
Assert.Equal("3", result); Assert.Equal("3", result);
} }

View File

@@ -50,7 +50,7 @@ public class Day04_Tests
[Fact] [Fact]
public void GuardEvent_FromStringArray__TestBase() public void GuardEvent_FromStringArray__TestBase()
{ {
List<Day04.GuardEvent> guardEvents = Day04.GuardEvent.FromStringArray([ List<Day04.GuardEvent> guardEvents = Day04.GuardEvent.FromStringArray(new[] {
"[1518-11-01 00:00] Guard #10 begins shift", "[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep", "[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up", "[1518-11-01 00:25] wakes up",
@@ -59,7 +59,7 @@ public class Day04_Tests
"[1518-11-01 23:58] Guard #99 begins shift", "[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-02 00:40] falls asleep", "[1518-11-02 00:40] falls asleep",
"[1518-11-02 00:50] wakes up", "[1518-11-02 00:50] wakes up",
]); });
Assert.Equal(10, guardEvents[0].ID); Assert.Equal(10, guardEvents[0].ID);
Assert.Equal(Day04.GuardEventType.ShiftBegin, guardEvents[0].Type); Assert.Equal(Day04.GuardEventType.ShiftBegin, guardEvents[0].Type);
@@ -89,7 +89,7 @@ public class Day04_Tests
[Fact] [Fact]
public void GuardEvent_FromStringArray__TestBaseUnsorted() public void GuardEvent_FromStringArray__TestBaseUnsorted()
{ {
List<Day04.GuardEvent> guardEvents = Day04.GuardEvent.FromStringArray([ List<Day04.GuardEvent> guardEvents = Day04.GuardEvent.FromStringArray(new[] {
"[1518-11-01 00:00] Guard #10 begins shift", "[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 23:58] Guard #99 begins shift", "[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-01 00:30] falls asleep", "[1518-11-01 00:30] falls asleep",
@@ -98,7 +98,7 @@ public class Day04_Tests
"[1518-11-02 00:50] wakes up", "[1518-11-02 00:50] wakes up",
"[1518-11-01 00:55] wakes up", "[1518-11-01 00:55] wakes up",
"[1518-11-01 00:25] wakes up", "[1518-11-01 00:25] wakes up",
]); });
Assert.Equal(10, guardEvents[0].ID); Assert.Equal(10, guardEvents[0].ID);
Assert.Equal(Day04.GuardEventType.ShiftBegin, guardEvents[0].Type); Assert.Equal(Day04.GuardEventType.ShiftBegin, guardEvents[0].Type);
@@ -132,7 +132,7 @@ public class Day04_Tests
{ {
Day04 day04 = new(); Day04 day04 = new();
string result = day04.ResolvePart1([ string result = day04.ResolvePart1(new[] {
"[1518-11-01 00:00] Guard #10 begins shift", "[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep", "[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up", "[1518-11-01 00:25] wakes up",
@@ -150,7 +150,7 @@ public class Day04_Tests
"[1518-11-05 00:03] Guard #99 begins shift", "[1518-11-05 00:03] Guard #99 begins shift",
"[1518-11-05 00:45] falls asleep", "[1518-11-05 00:45] falls asleep",
"[1518-11-05 00:55] wakes up", "[1518-11-05 00:55] wakes up",
]); });
Assert.Equal("240", result); Assert.Equal("240", result);
} }
@@ -160,7 +160,7 @@ public class Day04_Tests
{ {
Day04 day04 = new(); Day04 day04 = new();
string result = day04.ResolvePart1([ string result = day04.ResolvePart1(new[] {
"[1518-11-04 00:36] falls asleep", "[1518-11-04 00:36] falls asleep",
"[1518-11-04 00:46] wakes up", "[1518-11-04 00:46] wakes up",
"[1518-11-05 00:03] Guard #99 begins shift", "[1518-11-05 00:03] Guard #99 begins shift",
@@ -178,7 +178,7 @@ public class Day04_Tests
"[1518-11-01 00:55] wakes up", "[1518-11-01 00:55] wakes up",
"[1518-11-01 23:58] Guard #99 begins shift", "[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-05 00:55] wakes up", "[1518-11-05 00:55] wakes up",
]); });
Assert.Equal("240", result); Assert.Equal("240", result);
} }
@@ -189,7 +189,7 @@ public class Day04_Tests
{ {
Day04 day04 = new(); Day04 day04 = new();
string result = day04.ResolvePart2([ string result = day04.ResolvePart2(new[] {
"[1518-11-01 00:00] Guard #10 begins shift", "[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep", "[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up", "[1518-11-01 00:25] wakes up",
@@ -207,7 +207,7 @@ public class Day04_Tests
"[1518-11-05 00:03] Guard #99 begins shift", "[1518-11-05 00:03] Guard #99 begins shift",
"[1518-11-05 00:45] falls asleep", "[1518-11-05 00:45] falls asleep",
"[1518-11-05 00:55] wakes up", "[1518-11-05 00:55] wakes up",
]); });
Assert.Equal("4455", result); Assert.Equal("4455", result);
} }
@@ -217,7 +217,7 @@ public class Day04_Tests
{ {
Day04 day04 = new(); Day04 day04 = new();
string result = day04.ResolvePart2([ string result = day04.ResolvePart2(new[] {
"[1518-11-04 00:36] falls asleep", "[1518-11-04 00:36] falls asleep",
"[1518-11-04 00:46] wakes up", "[1518-11-04 00:46] wakes up",
"[1518-11-05 00:03] Guard #99 begins shift", "[1518-11-05 00:03] Guard #99 begins shift",
@@ -235,7 +235,7 @@ public class Day04_Tests
"[1518-11-01 00:55] wakes up", "[1518-11-01 00:55] wakes up",
"[1518-11-01 23:58] Guard #99 begins shift", "[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-05 00:55] wakes up", "[1518-11-05 00:55] wakes up",
]); });
Assert.Equal("4455", result); Assert.Equal("4455", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day05_Tests
{ {
Day05 day05 = new(); Day05 day05 = new();
string result = day05.ResolvePart1(["dabAcCaCBAcCcaDA"]); string result = day05.ResolvePart1(new[] { "dabAcCaCBAcCcaDA" });
Assert.Equal("10", result); Assert.Equal("10", result);
} }
@@ -17,7 +17,7 @@ public class Day05_Tests
{ {
Day05 day05 = new(); Day05 day05 = new();
string result = day05.ResolvePart2(["dabAcCaCBAcCcaDA"]); string result = day05.ResolvePart2(new[] { "dabAcCaCBAcCcaDA" });
Assert.Equal("4", result); Assert.Equal("4", result);
} }

View File

@@ -7,28 +7,28 @@ public class Day06_Tests
[Fact] [Fact]
public void ChronoPoint_FromString__Test1() public void ChronoPoint_FromString__Test1()
{ {
Day06.ChronoPoint? point = Day06.ChronoPoint.FromString("1, 1"); Day06.ChronoPoint point = Day06.ChronoPoint.FromString("1, 1");
Assert.Equal(1, point?.X); Assert.Equal(1, point.X);
Assert.Equal(1, point?.Y); Assert.Equal(1, point.Y);
} }
[Fact] [Fact]
public void ChronoPoint_FromString__Test2() public void ChronoPoint_FromString__Test2()
{ {
Day06.ChronoPoint? point = Day06.ChronoPoint.FromString("1, 6"); Day06.ChronoPoint point = Day06.ChronoPoint.FromString("1, 6");
Assert.Equal(1, point?.X); Assert.Equal(1, point.X);
Assert.Equal(6, point?.Y); Assert.Equal(6, point.Y);
} }
[Fact] [Fact]
public void ChronoPoint_FromString__Test3() public void ChronoPoint_FromString__Test3()
{ {
Day06.ChronoPoint? point = Day06.ChronoPoint.FromString("8, 9"); Day06.ChronoPoint point = Day06.ChronoPoint.FromString("8, 9");
Assert.Equal(8, point?.X); Assert.Equal(8, point.X);
Assert.Equal(9, point?.Y); Assert.Equal(9, point.Y);
} }
#endregion ChronoPoint_FromString #endregion ChronoPoint_FromString
@@ -38,11 +38,8 @@ public class Day06_Tests
[Fact] [Fact]
public void ChronoPoint_ManhattanDistance__Test1() public void ChronoPoint_ManhattanDistance__Test1()
{ {
Day06.ChronoPoint? p0 = Day06.ChronoPoint.FromString("8, 9"); Day06.ChronoPoint p0 = Day06.ChronoPoint.FromString("8, 9");
Day06.ChronoPoint? p1 = Day06.ChronoPoint.FromString("1, 6"); Day06.ChronoPoint p1 = Day06.ChronoPoint.FromString("1, 6");
Assert.NotNull(p0);
Assert.NotNull(p1);
int distance = Day06.ChronoPoint.ManhattanDistance(p0, p1); int distance = Day06.ChronoPoint.ManhattanDistance(p0, p1);
@@ -52,11 +49,8 @@ public class Day06_Tests
[Fact] [Fact]
public void ChronoPoint_ManhattanDistance__Test2() public void ChronoPoint_ManhattanDistance__Test2()
{ {
Day06.ChronoPoint? p0 = Day06.ChronoPoint.FromString("1, 1"); Day06.ChronoPoint p0 = Day06.ChronoPoint.FromString("1, 1");
Day06.ChronoPoint? p1 = Day06.ChronoPoint.FromString("1, 6"); Day06.ChronoPoint p1 = Day06.ChronoPoint.FromString("1, 6");
Assert.NotNull(p0);
Assert.NotNull(p1);
int distance = Day06.ChronoPoint.ManhattanDistance(p0, p1); int distance = Day06.ChronoPoint.ManhattanDistance(p0, p1);
@@ -70,14 +64,14 @@ public class Day06_Tests
{ {
Day06 day06 = new(); Day06 day06 = new();
string result = day06.ResolvePart1([ string result = day06.ResolvePart1(new[] {
"1, 1", "1, 1",
"1, 6", "1, 6",
"8, 3", "8, 3",
"3, 4", "3, 4",
"5, 5", "5, 5",
"8, 9", "8, 9",
]); });
Assert.Equal("17", result); Assert.Equal("17", result);
} }
@@ -85,16 +79,16 @@ public class Day06_Tests
[Fact] [Fact]
public void ResolvePart2__Test() public void ResolvePart2__Test()
{ {
Day06 day06 = new() { DistanceThreshold = 32, }; Day06 day06 = new() { DistanceThresold = 32, };
string result = day06.ResolvePart2([ string result = day06.ResolvePart2(new[] {
"1, 1", "1, 1",
"1, 6", "1, 6",
"8, 3", "8, 3",
"3, 4", "3, 4",
"5, 5", "5, 5",
"8, 9", "8, 9",
]); });
Assert.Equal("16", result); Assert.Equal("16", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day07_Tests
{ {
Day07 day07 = new(); Day07 day07 = new();
string result = day07.ResolvePart1([ string result = day07.ResolvePart1(new[] {
"Step C must be finished before step A can begin.", "Step C must be finished before step A can begin.",
"Step C must be finished before step F can begin.", "Step C must be finished before step F can begin.",
"Step A must be finished before step B can begin.", "Step A must be finished before step B can begin.",
@@ -15,7 +15,7 @@ public class Day07_Tests
"Step B must be finished before step E can begin.", "Step B must be finished before step E can begin.",
"Step D must be finished before step E can begin.", "Step D must be finished before step E can begin.",
"Step F must be finished before step E can begin.", "Step F must be finished before step E can begin.",
]); });
Assert.Equal("CABDFE", result); Assert.Equal("CABDFE", result);
} }
@@ -25,7 +25,7 @@ public class Day07_Tests
{ {
Day07 day07 = new() { BaseCost = 0, NumberOfWorkers = 2 }; Day07 day07 = new() { BaseCost = 0, NumberOfWorkers = 2 };
string result = day07.ResolvePart2([ string result = day07.ResolvePart2(new[] {
"Step C must be finished before step A can begin.", "Step C must be finished before step A can begin.",
"Step C must be finished before step F can begin.", "Step C must be finished before step F can begin.",
"Step A must be finished before step B can begin.", "Step A must be finished before step B can begin.",
@@ -33,7 +33,7 @@ public class Day07_Tests
"Step B must be finished before step E can begin.", "Step B must be finished before step E can begin.",
"Step D must be finished before step E can begin.", "Step D must be finished before step E can begin.",
"Step F must be finished before step E can begin.", "Step F must be finished before step E can begin.",
]); });
Assert.Equal("15", result); Assert.Equal("15", result);
} }

View File

@@ -34,7 +34,7 @@ public class Day08_Tests
{ {
Day08 day = new(); Day08 day = new();
string result = day.ResolvePart1(["2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"]); string result = day.ResolvePart1(new[] { "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2", });
Assert.Equal("138", result); Assert.Equal("138", result);
} }
@@ -44,7 +44,7 @@ public class Day08_Tests
{ {
Day08 day = new(); Day08 day = new();
string result = day.ResolvePart2(["2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"]); string result = day.ResolvePart2(new[] { "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2", });
Assert.Equal("66", result); Assert.Equal("66", result);
} }

View File

@@ -77,7 +77,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["9 players; last marble is worth 25 points"]); string result = day.ResolvePart1(new[] { "9 players; last marble is worth 25 points" });
Assert.Equal("32", result); Assert.Equal("32", result);
} }
@@ -87,7 +87,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["10 players; last marble is worth 1618 points"]); string result = day.ResolvePart1(new[] { "10 players; last marble is worth 1618 points" });
Assert.Equal("8317", result); Assert.Equal("8317", result);
} }
@@ -97,7 +97,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["13 players; last marble is worth 7999 points"]); string result = day.ResolvePart1(new[] { "13 players; last marble is worth 7999 points" });
Assert.Equal("146373", result); Assert.Equal("146373", result);
} }
@@ -107,7 +107,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["17 players; last marble is worth 1104 points"]); string result = day.ResolvePart1(new[] { "17 players; last marble is worth 1104 points" });
Assert.Equal("2764", result); Assert.Equal("2764", result);
} }
@@ -117,7 +117,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["21 players; last marble is worth 6111 points"]); string result = day.ResolvePart1(new[] { "21 players; last marble is worth 6111 points" });
Assert.Equal("54718", result); Assert.Equal("54718", result);
} }
@@ -127,7 +127,7 @@ public class Day09_Tests
{ {
Day09 day = new(); Day09 day = new();
string result = day.ResolvePart1(["30 players; last marble is worth 5807 points"]); string result = day.ResolvePart1(new[] { "30 players; last marble is worth 5807 points" });
Assert.Equal("37305", result); Assert.Equal("37305", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day10_Tests
{ {
Day10 day = new() { Width = 12, Height = 10 }; Day10 day = new() { Width = 12, Height = 10 };
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"position=< 9, 1> velocity=< 0, 2>", "position=< 9, 1> velocity=< 0, 2>",
"position=< 7, 0> velocity=<-1, 0>", "position=< 7, 0> velocity=<-1, 0>",
"position=< 3, -2> velocity=<-1, 1>", "position=< 3, -2> velocity=<-1, 1>",
@@ -39,7 +39,7 @@ public class Day10_Tests
"position=< 5, 9> velocity=< 1, -2>", "position=< 5, 9> velocity=< 1, -2>",
"position=<14, 7> velocity=<-2, 0>", "position=<14, 7> velocity=<-2, 0>",
"position=<-3, 6> velocity=< 2, -1>", "position=<-3, 6> velocity=< 2, -1>",
]); });
Assert.Equal( Assert.Equal(
Environment.NewLine + "............" + Environment.NewLine + "............" +
@@ -59,7 +59,7 @@ public class Day10_Tests
{ {
Day10 day = new(); Day10 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"position=< 9, 1> velocity=< 0, 2>", "position=< 9, 1> velocity=< 0, 2>",
"position=< 7, 0> velocity=<-1, 0>", "position=< 7, 0> velocity=<-1, 0>",
"position=< 3, -2> velocity=<-1, 1>", "position=< 3, -2> velocity=<-1, 1>",
@@ -91,7 +91,7 @@ public class Day10_Tests
"position=< 5, 9> velocity=< 1, -2>", "position=< 5, 9> velocity=< 1, -2>",
"position=<14, 7> velocity=<-2, 0>", "position=<14, 7> velocity=<-2, 0>",
"position=<-3, 6> velocity=< 2, -1>", "position=<-3, 6> velocity=< 2, -1>",
]); });
Assert.Equal("3", result); Assert.Equal("3", result);
} }

View File

@@ -59,7 +59,7 @@ public class Day11_Tests
public void ResolvePart2__Test1() public void ResolvePart2__Test1()
{ {
Day11 day = new(); Day11 day = new();
string result = day.ResolvePart2(["18"]); string result = day.ResolvePart2(new[] { "18" });
Assert.Equal("90,269,16", result); Assert.Equal("90,269,16", result);
} }
@@ -67,7 +67,7 @@ public class Day11_Tests
public void ResolvePart2__Test2() public void ResolvePart2__Test2()
{ {
Day11 day = new(); Day11 day = new();
string result = day.ResolvePart2(["42"]); string result = day.ResolvePart2(new[] { "42" });
Assert.Equal("232,251,12", result); Assert.Equal("232,251,12", result);
} }
} }

View File

@@ -7,7 +7,8 @@ public class Day12_Tests
{ {
Day12 day = new(); Day12 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[]
{
"initial state: #..#.#..##......###...###", "initial state: #..#.#..##......###...###",
"", "",
"...## => #", "...## => #",
@@ -24,7 +25,7 @@ public class Day12_Tests
"###.. => #", "###.. => #",
"###.# => #", "###.# => #",
"####. => #", "####. => #",
]); });
Assert.Equal("325", result); Assert.Equal("325", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day13_Tests
{ {
Day13 day = new(); Day13 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"|", "|",
"v", "v",
"|", "|",
@@ -15,7 +15,7 @@ public class Day13_Tests
"|", "|",
"^", "^",
"|", "|",
]); });
Assert.Equal("0,3", result); Assert.Equal("0,3", result);
} }
@@ -25,14 +25,14 @@ public class Day13_Tests
{ {
Day13 day = new(); Day13 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
@"/->-\ ", @"/->-\ ",
@"| | /----\", @"| | /----\",
@"| /-+--+-\ |", @"| /-+--+-\ |",
@"| | | | v |", @"| | | | v |",
@"\-+-/ \-+--/", @"\-+-/ \-+--/",
@" \------/ ", @" \------/ ",
]); });
Assert.Equal("7,3", result); Assert.Equal("7,3", result);
} }
@@ -42,7 +42,7 @@ public class Day13_Tests
{ {
Day13 day = new(); Day13 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
@"/>-<\ ", @"/>-<\ ",
@"| | ", @"| | ",
@"| /<+-\", @"| /<+-\",
@@ -50,7 +50,7 @@ public class Day13_Tests
@"\>+</ |", @"\>+</ |",
@" | ^", @" | ^",
@" \<->/", @" \<->/",
]); });
Assert.Equal("6,4", result); Assert.Equal("6,4", result);
} }

View File

@@ -9,7 +9,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart1(["9"]); string result = day.ResolvePart1(new[] { "9", });
Assert.Equal("5158916779", result); Assert.Equal("5158916779", result);
} }
@@ -19,7 +19,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart1(["5"]); string result = day.ResolvePart1(new[] { "5", });
Assert.Equal("0124515891", result); Assert.Equal("0124515891", result);
} }
@@ -29,7 +29,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart1(["18"]); string result = day.ResolvePart1(new[] { "18", });
Assert.Equal("9251071085", result); Assert.Equal("9251071085", result);
} }
@@ -39,7 +39,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart1(["2018"]); string result = day.ResolvePart1(new[] { "2018", });
Assert.Equal("5941429882", result); Assert.Equal("5941429882", result);
} }
@@ -53,7 +53,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart2(["51589"]); string result = day.ResolvePart2(new[] { "51589", });
Assert.Equal("9", result); Assert.Equal("9", result);
} }
@@ -63,7 +63,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart2(["01245"]); string result = day.ResolvePart2(new[] { "01245", });
Assert.Equal("5", result); Assert.Equal("5", result);
} }
@@ -73,7 +73,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart2(["92510"]); string result = day.ResolvePart2(new[] { "92510", });
Assert.Equal("18", result); Assert.Equal("18", result);
} }
@@ -83,7 +83,7 @@ public class Day14_Tests
{ {
Day14 day = new(); Day14 day = new();
string result = day.ResolvePart2(["59414"]); string result = day.ResolvePart2(new[] { "59414", });
Assert.Equal("2018", result); Assert.Equal("2018", result);
} }

View File

@@ -9,7 +9,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#######", "#######",
"#.G...#", "#.G...#",
"#...EG#", "#...EG#",
@@ -17,7 +17,7 @@ public class Day15_Tests
"#..G#E#", "#..G#E#",
"#.....#", "#.....#",
"#######", "#######",
]); });
Assert.Equal("27730", result); Assert.Equal("27730", result);
} }
@@ -27,7 +27,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#######", "#######",
"#G..#E#", "#G..#E#",
"#E#E.E#", "#E#E.E#",
@@ -35,7 +35,7 @@ public class Day15_Tests
"#...#E#", "#...#E#",
"#...E.#", "#...E.#",
"#######", "#######",
]); });
Assert.Equal("36334", result); Assert.Equal("36334", result);
} }
@@ -45,7 +45,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#######", "#######",
"#E..EG#", "#E..EG#",
"#.#G.E#", "#.#G.E#",
@@ -53,7 +53,7 @@ public class Day15_Tests
"#G..#.#", "#G..#.#",
"#..E#.#", "#..E#.#",
"#######", "#######",
]); });
Assert.Equal("39514", result); Assert.Equal("39514", result);
} }
@@ -63,7 +63,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#######", "#######",
"#E.G#.#", "#E.G#.#",
"#.#G..#", "#.#G..#",
@@ -71,7 +71,7 @@ public class Day15_Tests
"#G..#.#", "#G..#.#",
"#...E.#", "#...E.#",
"#######", "#######",
]); });
Assert.Equal("27755", result); Assert.Equal("27755", result);
} }
@@ -81,7 +81,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#######", "#######",
"#.E...#", "#.E...#",
"#.#..G#", "#.#..G#",
@@ -89,7 +89,7 @@ public class Day15_Tests
"#E#G#G#", "#E#G#G#",
"#...#G#", "#...#G#",
"#######", "#######",
]); });
Assert.Equal("28944", result); Assert.Equal("28944", result);
} }
@@ -99,7 +99,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"#########", "#########",
"#G......#", "#G......#",
"#.E.#...#", "#.E.#...#",
@@ -109,7 +109,7 @@ public class Day15_Tests
"#.G...G.#", "#.G...G.#",
"#.....G.#", "#.....G.#",
"#########", "#########",
]); });
Assert.Equal("18740", result); Assert.Equal("18740", result);
} }
@@ -123,7 +123,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"#######", "#######",
"#.G...#", "#.G...#",
"#...EG#", "#...EG#",
@@ -131,7 +131,7 @@ public class Day15_Tests
"#..G#E#", "#..G#E#",
"#.....#", "#.....#",
"#######", "#######",
]); });
Assert.Equal("4988", result); Assert.Equal("4988", result);
} }
@@ -141,7 +141,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"#######", "#######",
"#E..EG#", "#E..EG#",
"#.#G.E#", "#.#G.E#",
@@ -149,7 +149,7 @@ public class Day15_Tests
"#G..#.#", "#G..#.#",
"#..E#.#", "#..E#.#",
"#######", "#######",
]); });
Assert.Equal("31284", result); Assert.Equal("31284", result);
} }
@@ -159,7 +159,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"#######", "#######",
"#E.G#.#", "#E.G#.#",
"#.#G..#", "#.#G..#",
@@ -167,7 +167,7 @@ public class Day15_Tests
"#G..#.#", "#G..#.#",
"#...E.#", "#...E.#",
"#######", "#######",
]); });
Assert.Equal("3478", result); Assert.Equal("3478", result);
} }
@@ -177,7 +177,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"#######", "#######",
"#.E...#", "#.E...#",
"#.#..G#", "#.#..G#",
@@ -185,7 +185,7 @@ public class Day15_Tests
"#E#G#G#", "#E#G#G#",
"#...#G#", "#...#G#",
"#######", "#######",
]); });
Assert.Equal("6474", result); Assert.Equal("6474", result);
} }
@@ -195,7 +195,7 @@ public class Day15_Tests
{ {
Day15 day = new(); Day15 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"#########", "#########",
"#G......#", "#G......#",
"#.E.#...#", "#.E.#...#",
@@ -205,7 +205,7 @@ public class Day15_Tests
"#.G...G.#", "#.G...G.#",
"#.....G.#", "#.....G.#",
"#########", "#########",
]); });
Assert.Equal("1140", result); Assert.Equal("1140", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day16_Tests
{ {
Day16 day = new(); Day16 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"Before: [3, 2, 1, 1]", "Before: [3, 2, 1, 1]",
"9 2 1 2", "9 2 1 2",
"After: [3, 2, 2, 1]", "After: [3, 2, 2, 1]",
@@ -18,7 +18,7 @@ public class Day16_Tests
"", "",
"", "",
"Garbage", "Garbage",
]); });
Assert.Equal("2", result); Assert.Equal("2", result);
} }

View File

@@ -7,7 +7,7 @@ public class Day23_Tests
{ {
Day23 day = new(); Day23 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"pos=<0,0,0>, r=4", "pos=<0,0,0>, r=4",
"pos=<1,0,0>, r=1", "pos=<1,0,0>, r=1",
"pos=<4,0,0>, r=3", "pos=<4,0,0>, r=3",
@@ -17,7 +17,7 @@ public class Day23_Tests
"pos=<1,1,1>, r=1", "pos=<1,1,1>, r=1",
"pos=<1,1,2>, r=1", "pos=<1,1,2>, r=1",
"pos=<1,3,1>, r=1", "pos=<1,3,1>, r=1",
]); });
Assert.Equal("7", result); Assert.Equal("7", result);
} }
@@ -27,14 +27,14 @@ public class Day23_Tests
{ {
Day23 day = new(); Day23 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"pos=<10,12,12>, r=2", "pos=<10,12,12>, r=2",
"pos=<12,14,12>, r=2", "pos=<12,14,12>, r=2",
"pos=<16,12,12>, r=4", "pos=<16,12,12>, r=4",
"pos=<14,14,14>, r=6", "pos=<14,14,14>, r=6",
"pos=<50,50,50>, r=200", "pos=<50,50,50>, r=200",
"pos=<10,10,10>, r=5", "pos=<10,10,10>, r=5",
]); });
Assert.Equal("36", result); Assert.Equal("36", result);
} }

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="MSTest.TestAdapter" version="1.4.0" targetFramework="net461"/> <package id="MSTest.TestAdapter" version="1.4.0" targetFramework="net461" />
<package id="MSTest.TestFramework" version="1.4.0" targetFramework="net461"/> <package id="MSTest.TestFramework" version="1.4.0" targetFramework="net461" />
</packages> </packages>

View File

@@ -2,9 +2,8 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2018</RootNamespace> <RootNamespace>AdventOfCode2018</RootNamespace>
</PropertyGroup> </PropertyGroup>
@@ -15,7 +14,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj"/> <ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -63,7 +63,8 @@ public class Day01 : IDay
int accumulator = 0; int accumulator = 0;
foreach (string input in inputs) foreach (string input in inputs)
{ {
if (int.TryParse(input.Substring(1), out int intInput)) int intInput;
if (int.TryParse(input.Substring(1), out intInput))
{ {
if (input[0] == '-') if (input[0] == '-')
{ {
@@ -82,14 +83,15 @@ public class Day01 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
int accumulator = 0; int accumulator = 0;
List<int> accumulatorHistory = []; List<int> accumulatorHistory = new();
int? repeatedAccumulator = null; int? repeatedAccumulator = null;
while (repeatedAccumulator == null) while (repeatedAccumulator == null)
{ {
foreach (string input in inputs) foreach (string input in inputs)
{ {
accumulatorHistory.Add(accumulator); accumulatorHistory.Add(accumulator);
if (int.TryParse(input.Substring(1), out int intInput)) int intInput;
if (int.TryParse(input.Substring(1), out intInput))
{ {
if (input[0] == '-') if (input[0] == '-')
{ {
@@ -108,6 +110,6 @@ public class Day01 : IDay
} }
} }
} }
return repeatedAccumulator.ToString() ?? string.Empty; return repeatedAccumulator.ToString();
} }
} }

View File

@@ -50,7 +50,7 @@ What letters are common between the two correct box IDs? (In the example above,
public class Day02 : IDay public class Day02 : IDay
{ {
private static int CountOccurrencesOfLetter(string text, char letter) private int CountOccurrencesOfLetter(string text, char letter)
{ {
return text.Count(c => (c == letter)); return text.Count(c => (c == letter));
} }
@@ -75,7 +75,7 @@ public class Day02 : IDay
int tripletsCount = 0; int tripletsCount = 0;
foreach (string input in inputs) foreach (string input in inputs)
{ {
Tuple<bool, bool> hasPairsAndTriplets = HasPairsAndTriplets(input); var hasPairsAndTriplets = HasPairsAndTriplets(input);
if (hasPairsAndTriplets.Item1) { pairsCount++; } if (hasPairsAndTriplets.Item1) { pairsCount++; }
if (hasPairsAndTriplets.Item2) { tripletsCount++; } if (hasPairsAndTriplets.Item2) { tripletsCount++; }
} }
@@ -104,10 +104,11 @@ public class Day02 : IDay
{ {
for (int j = (i + 1); j < inputs.Length; j++) for (int j = (i + 1); j < inputs.Length; j++)
{ {
Tuple<int, string> result = CompareIDPair(inputs[i], inputs[j]); var result = CompareIDPair(inputs[i], inputs[j]);
if (result.Item1 == 1) { return result.Item2; } if (result.Item1 == 1) { return result.Item2; }
} }
} }
return string.Empty; return string.Empty;
} }
} }

View File

@@ -60,7 +60,7 @@ public class Day03 : IDay
{ {
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
List<Claim> claims = inputs.Select(Claim.FromString).ToList(); List<Claim> claims = inputs.Select(i => Claim.FromString(i)).ToList();
const int edgeSize = 1000; const int edgeSize = 1000;
int[,] cells = new int[edgeSize, edgeSize]; int[,] cells = new int[edgeSize, edgeSize];
@@ -92,9 +92,9 @@ public class Day03 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
List<Claim> claims = inputs.Select(Claim.FromString).ToList(); List<Claim> claims = inputs.Select(i => Claim.FromString(i)).ToList();
Claim? unOverlappingClaim = null; Claim unoverlappingClaim = null;
for (int i = 0; i < claims.Count; i++) for (int i = 0; i < claims.Count; i++)
{ {
bool overlaps = false; bool overlaps = false;
@@ -109,43 +109,29 @@ public class Day03 : IDay
} }
if (overlaps == false) if (overlaps == false)
{ {
unOverlappingClaim = claims[i]; unoverlappingClaim = claims[i];
break; break;
} }
} }
return unOverlappingClaim?.ID.ToString() ?? string.Empty; return unoverlappingClaim.ID.ToString();
} }
public class Claim public class Claim
{ {
public int ID { get; private set; } public int ID { get; set; }
public int Left { get; private set; } public int Left { get; set; }
public int Top { get; private set; } public int Top { get; set; }
public int Width { get; private set; } public int Width { get; set; }
public int Height { get; private set; } public int Height { get; set; }
private int MinX public int MinX { get { return Left; } }
{ public int MaxX { get { return Left + Width; } }
get { return Left; }
}
private int MaxX public int MinY { get { return Top; } }
{ public int MaxY { get { return Top + Height; } }
get { return Left + Width; }
}
private int MinY
{
get { return Top; }
}
private int MaxY
{
get { return Top + Height; }
}
public int GetArea() public int GetArea()
{ {
@@ -155,7 +141,7 @@ public class Day03 : IDay
public static Claim FromString(string strClaim) public static Claim FromString(string strClaim)
{ {
Claim claim = new(); Claim claim = new();
string[] parts = strClaim.Split([" @ ", ",", ": ", "x"], StringSplitOptions.None); string[] parts = strClaim.Split(new[] { " @ ", ",", ": ", "x", }, StringSplitOptions.None);
claim.ID = Convert.ToInt32(parts[0].Substring(1)); claim.ID = Convert.ToInt32(parts[0].Substring(1));
claim.Left = Convert.ToInt32(parts[1]); claim.Left = Convert.ToInt32(parts[1]);
claim.Top = Convert.ToInt32(parts[2]); claim.Top = Convert.ToInt32(parts[2]);

View File

@@ -68,14 +68,14 @@ public class Day04 : IDay
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs); List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistogram(guardEvents); Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistorgram(guardEvents);
// Find sleepier guard // Find sleepier guard
GuardSleepHistogram? highestSleeperHistogram = null; GuardSleepHistogram highestSleeperHistogram = null;
long highestTotalSleep = long.MinValue; long highestTotalSleep = long.MinValue;
foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values) foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values)
{ {
int totalSleep = guardHistogram.SleepOnMinute.Sum(); int totalSleep = guardHistogram.SleepOnMunute.Sum();
if (totalSleep > highestTotalSleep) if (totalSleep > highestTotalSleep)
{ {
@@ -83,17 +83,16 @@ public class Day04 : IDay
highestTotalSleep = totalSleep; highestTotalSleep = totalSleep;
} }
} }
if (highestSleeperHistogram == null) { return string.Empty; }
// Find sleepier minute // Find sleepier minute
int maxSleepMinute = int.MinValue; int maxSleepMinute = int.MinValue;
int maxSleepMinuteValue = int.MinValue; int maxSleepMinuteValue = int.MinValue;
for (int i = 0; i < GuardSleepHistogram.MinutesOnHour; i++) for (int i = 0; i < GuardSleepHistogram.MinutesOnHour; i++)
{ {
if (highestSleeperHistogram.SleepOnMinute[i] > maxSleepMinuteValue) if (highestSleeperHistogram.SleepOnMunute[i] > maxSleepMinuteValue)
{ {
maxSleepMinute = i; maxSleepMinute = i;
maxSleepMinuteValue = highestSleeperHistogram.SleepOnMinute[i]; maxSleepMinuteValue = highestSleeperHistogram.SleepOnMunute[i];
} }
} }
@@ -104,7 +103,7 @@ public class Day04 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs); List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistogram(guardEvents); Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistorgram(guardEvents);
int selectedGuardID = int.MinValue; int selectedGuardID = int.MinValue;
int selectedMinute = int.MinValue; int selectedMinute = int.MinValue;
@@ -113,9 +112,9 @@ public class Day04 : IDay
{ {
foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values) foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values)
{ {
if (guardHistogram.SleepOnMinute[i] > maxSleepMinuteValue) if (guardHistogram.SleepOnMunute[i] > maxSleepMinuteValue)
{ {
maxSleepMinuteValue = guardHistogram.SleepOnMinute[i]; maxSleepMinuteValue = guardHistogram.SleepOnMunute[i];
selectedGuardID = guardHistogram.ID; selectedGuardID = guardHistogram.ID;
selectedMinute = i; selectedMinute = i;
} }
@@ -126,7 +125,7 @@ public class Day04 : IDay
return result.ToString(); return result.ToString();
} }
private static Dictionary<int, GuardSleepHistogram> BuildFullHistogram(List<GuardEvent> guardEvents) private static Dictionary<int, GuardSleepHistogram> BuildFullHistorgram(List<GuardEvent> guardEvents)
{ {
Dictionary<int, GuardSleepHistogram> dictFullHistogram = new(); Dictionary<int, GuardSleepHistogram> dictFullHistogram = new();
foreach (IGrouping<int, GuardEvent> group in guardEvents.GroupBy(guardEvent => guardEvent.Date.DayOfYear)) foreach (IGrouping<int, GuardEvent> group in guardEvents.GroupBy(guardEvent => guardEvent.Date.DayOfYear))
@@ -157,14 +156,18 @@ public class Day04 : IDay
foreach (GuardSleepHistogram dayGuardHistogram in dictDayHistogram.Values) foreach (GuardSleepHistogram dayGuardHistogram in dictDayHistogram.Values)
{ {
if (dictFullHistogram.TryGetValue(dayGuardHistogram.ID, out GuardSleepHistogram? guardHistogram)) GuardSleepHistogram guardHistogram;
if (dictFullHistogram.ContainsKey(dayGuardHistogram.ID))
{ {
guardHistogram = dictFullHistogram[dayGuardHistogram.ID];
guardHistogram.AddHistogram(dayGuardHistogram); guardHistogram.AddHistogram(dayGuardHistogram);
continue;
} }
else
{
dictFullHistogram.Add(dayGuardHistogram.ID, dayGuardHistogram); dictFullHistogram.Add(dayGuardHistogram.ID, dayGuardHistogram);
} }
} }
}
return dictFullHistogram; return dictFullHistogram;
} }
@@ -178,14 +181,14 @@ public class Day04 : IDay
public class GuardEvent public class GuardEvent
{ {
public DateTime Date { get; private set; } public DateTime Date { get; set; }
public int? ID { get; private set; } public int? ID { get; set; }
public GuardEventType Type { get; private set; } public GuardEventType Type { get; set; }
public static GuardEvent FromString(string strEvent) public static GuardEvent FromString(string strEvent)
{ {
GuardEvent guardEvent = new(); GuardEvent guardEvent = new();
string[] parts = strEvent.Split(["[", "-", " ", ":", "]", "#"], StringSplitOptions.RemoveEmptyEntries); string[] parts = strEvent.Split(new[] { "[", "-", " ", ":", "]", "#", }, StringSplitOptions.RemoveEmptyEntries);
guardEvent.Date = new DateTime( guardEvent.Date = new DateTime(
Convert.ToInt32(parts[0]), Convert.ToInt32(parts[0]),
Convert.ToInt32(parts[1]), Convert.ToInt32(parts[1]),
@@ -213,7 +216,7 @@ public class Day04 : IDay
public static List<GuardEvent> FromStringArray(string[] strEvents) public static List<GuardEvent> FromStringArray(string[] strEvents)
{ {
List<GuardEvent> guardEvents = strEvents List<GuardEvent> guardEvents = strEvents
.Select(FromString) .Select(strEvent => FromString(strEvent))
.OrderBy(guardEvent => guardEvent.Date) .OrderBy(guardEvent => guardEvent.Date)
.ToList(); .ToList();
@@ -237,14 +240,14 @@ public class Day04 : IDay
public class GuardSleepHistogram public class GuardSleepHistogram
{ {
public const int MinutesOnHour = 60; public const int MinutesOnHour = 60;
public int ID { get; init; } public int ID { get; set; }
public int[] SleepOnMinute { get; } = new int[MinutesOnHour]; public int[] SleepOnMunute { get; } = new int[MinutesOnHour];
public void FallSleep(int minute) public void FallSleep(int minute)
{ {
for (int i = minute; i < MinutesOnHour; i++) for (int i = minute; i < MinutesOnHour; i++)
{ {
SleepOnMinute[i] = 1; SleepOnMunute[i] = 1;
} }
} }
@@ -252,7 +255,7 @@ public class Day04 : IDay
{ {
for (int i = minute; i < MinutesOnHour; i++) for (int i = minute; i < MinutesOnHour; i++)
{ {
SleepOnMinute[i] = 0; SleepOnMunute[i] = 0;
} }
} }
@@ -260,7 +263,7 @@ public class Day04 : IDay
{ {
for (int i = 0; i < MinutesOnHour; i++) for (int i = 0; i < MinutesOnHour; i++)
{ {
SleepOnMinute[i] += histogram.SleepOnMinute[i]; SleepOnMunute[i] += histogram.SleepOnMunute[i];
} }
} }
} }

View File

@@ -108,7 +108,7 @@ public class Day05 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
string input = inputs[0]; string input = inputs[0];
List<char> allUnitTypes = input.Select(char.ToLower).Distinct().ToList(); List<char> allUnitTypes = input.Select(c => char.ToLower(c)).Distinct().ToList();
int minPolymerLenght = int.MaxValue; int minPolymerLenght = int.MaxValue;
foreach (char unitType in allUnitTypes) foreach (char unitType in allUnitTypes)

View File

@@ -96,8 +96,7 @@ public class Day06 : IDay
{ {
return inputs return inputs
.Where(input => string.IsNullOrEmpty(input) == false) .Where(input => string.IsNullOrEmpty(input) == false)
.Select(ChronoPoint.FromString) .Select(input => ChronoPoint.FromString(input))
.OfType<ChronoPoint>()
.ToList(); .ToList();
} }
@@ -184,12 +183,12 @@ public class Day06 : IDay
return areaInRange; return areaInRange;
} }
public int DistanceThreshold { get; init; } = 10000; public int DistanceThresold { get; set; } = 10000;
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
List<ChronoPoint> points = InputsToPoints(inputs); List<ChronoPoint> points = InputsToPoints(inputs);
int areaInRange = AreaInThresold(points, DistanceThreshold); int areaInRange = AreaInThresold(points, DistanceThresold);
return areaInRange.ToString(); return areaInRange.ToString();
} }
@@ -198,10 +197,10 @@ public class Day06 : IDay
public int X { get; set; } public int X { get; set; }
public int Y { get; set; } public int Y { get; set; }
public static ChronoPoint? FromString(string strPoint) public static ChronoPoint FromString(string strPoint)
{ {
if (string.IsNullOrEmpty(strPoint)) { return null; } if (string.IsNullOrEmpty(strPoint)) { return null; }
string[] parts = strPoint.Split([", "], StringSplitOptions.RemoveEmptyEntries); string[] parts = strPoint.Split(new[] { ", ", }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) { return null; } if (parts.Length < 2) { return null; }
ChronoPoint point = new() { ChronoPoint point = new() {
X = Convert.ToInt32(parts[0]), X = Convert.ToInt32(parts[0]),

View File

@@ -89,11 +89,11 @@ public class Day07 : IDay
foreach (string input in inputs) foreach (string input in inputs)
{ {
if (string.IsNullOrEmpty(input)) { continue; } if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split([ string[] parts = input.Split(new[] {
"Step ", "Step ",
" must be finished before step ", " must be finished before step ",
" can begin.", " can begin.",
], StringSplitOptions.RemoveEmptyEntries); }, StringSplitOptions.RemoveEmptyEntries);
instructions.AddNodeRelation(parts[1].ToUpper(), parts[0].ToUpper()); instructions.AddNodeRelation(parts[1].ToUpper(), parts[0].ToUpper());
} }
foreach (InstructionNode node in instructions.Nodes.Values) foreach (InstructionNode node in instructions.Nodes.Values)
@@ -118,8 +118,8 @@ public class Day07 : IDay
return sbInstructions.ToString(); return sbInstructions.ToString();
} }
public int BaseCost { get; init; } = 60; public int BaseCost { get; set; } = 60;
public int NumberOfWorkers { get; init; } = 5; public int NumberOfWorkers { get; set; } = 5;
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
@@ -128,11 +128,11 @@ public class Day07 : IDay
return totalElapsedTime.ToString(); return totalElapsedTime.ToString();
} }
public class InstructionNode(string nodeID) public class InstructionNode
{ {
public string NodeID { get; init; } = nodeID; public string NodeID { get; set; }
public List<string> PreviousNodeIDs { get; } = []; public List<string> PreviousNodeIDs { get; } = new();
public int Cost { get; set; } public int Cost { get; set; }
@@ -148,18 +148,22 @@ public class Day07 : IDay
} }
} }
private class Instructions public class Instructions
{ {
public Dictionary<string, InstructionNode> Nodes { get; } = new(); public Dictionary<string, InstructionNode> Nodes { get; } = new();
private InstructionNode GetNode(string nodeID) public InstructionNode GetNode(string nodeID)
{ {
if (Nodes.TryGetValue(nodeID, out InstructionNode? nodeAux)) InstructionNode node = null;
if (Nodes.ContainsKey(nodeID))
{ {
return nodeAux; node = Nodes[nodeID];
} }
InstructionNode node = new(nodeID); else
{
node = new InstructionNode { NodeID = nodeID, };
Nodes.Add(nodeID, node); Nodes.Add(nodeID, node);
}
return node; return node;
} }
@@ -172,7 +176,7 @@ public class Day07 : IDay
public List<InstructionNode> SortInstructions() public List<InstructionNode> SortInstructions()
{ {
List<InstructionNode> finalNodes = []; List<InstructionNode> finalNodes = new();
foreach (InstructionNode node in Nodes.Values) foreach (InstructionNode node in Nodes.Values)
{ {
@@ -190,8 +194,7 @@ public class Day07 : IDay
.ToList(); .ToList();
if (unusedNodes.Count > 0) if (unusedNodes.Count > 0)
{ {
InstructionNode? node = unusedNodes.FirstOrDefault(); InstructionNode node = unusedNodes.FirstOrDefault();
if (node == null) { continue; }
finalNodes.Add(node); finalNodes.Add(node);
node.Used = true; node.Used = true;
} }
@@ -201,8 +204,8 @@ public class Day07 : IDay
private class SimulatedWorker private class SimulatedWorker
{ {
public InstructionNode? CurrentInstruction { get; private set; } public InstructionNode CurrentInstruction { get; set; }
private int ElapsedTime { get; set; } public int ElapsedTime { get; set; }
public void SetInstruction(InstructionNode instruction) public void SetInstruction(InstructionNode instruction)
{ {
@@ -239,6 +242,7 @@ public class Day07 : IDay
workers.Add(new SimulatedWorker()); workers.Add(new SimulatedWorker());
} }
bool anyWorkerWitoutWork;
do do
{ {
bool anyWorkDone = false; bool anyWorkDone = false;
@@ -251,8 +255,8 @@ public class Day07 : IDay
} }
if (anyWorkDone) { totalElapsedTime++; } if (anyWorkDone) { totalElapsedTime++; }
bool anyWorkerWithoutWork = workers.Any(w => w.CurrentInstruction == null); anyWorkerWitoutWork = workers.Any(w => w.CurrentInstruction == null);
if (anyWorkerWithoutWork) if (anyWorkerWitoutWork)
{ {
List<InstructionNode> unusedNodes = Nodes.Values List<InstructionNode> unusedNodes = Nodes.Values
.Where(n => .Where(n =>

View File

@@ -77,13 +77,13 @@ public class Day08 : IDay
public class IntStream public class IntStream
{ {
private readonly int[] _values; private int[] _values;
private int _index; private int _index;
public IntStream(string strValues) public IntStream(string strValues)
{ {
_values = strValues _values = strValues
.Split([" "], StringSplitOptions.RemoveEmptyEntries) .Split(new[] { " ", }, StringSplitOptions.RemoveEmptyEntries)
.Select(strVal => Convert.ToInt32(strVal)) .Select(strVal => Convert.ToInt32(strVal))
.ToArray(); .ToArray();
_index = 0; _index = 0;
@@ -99,9 +99,9 @@ public class Day08 : IDay
public class ChronoLicenceNode public class ChronoLicenceNode
{ {
public List<ChronoLicenceNode> Childs { get; } = []; public List<ChronoLicenceNode> Childs { get; } = new();
public List<int> Metadata { get; } = []; public List<int> Metadata { get; } = new();
public static ChronoLicenceNode BuildFromIntStream(IntStream stream) public static ChronoLicenceNode BuildFromIntStream(IntStream stream)
{ {

View File

@@ -75,7 +75,7 @@ public class Day09 : IDay
private static string CalculateHighScore(string input, long factor) private static string CalculateHighScore(string input, long factor)
{ {
string[] parts = input.Split([" players; last marble is worth ", " points"], StringSplitOptions.RemoveEmptyEntries); string[] parts = input.Split(new[] { " players; last marble is worth ", " points" }, StringSplitOptions.RemoveEmptyEntries);
long numberOfPlayers = Convert.ToInt32(parts[0]); long numberOfPlayers = Convert.ToInt32(parts[0]);
long lastMarble = Convert.ToInt32(parts[1]) * factor; long lastMarble = Convert.ToInt32(parts[1]) * factor;
MarbleGame marbleGame = new(); MarbleGame marbleGame = new();
@@ -86,17 +86,17 @@ public class Day09 : IDay
public class Marble public class Marble
{ {
public long Value { get; init; } public long Value { get; set; }
public Marble? Previous { get; set; } public Marble Previous { get; set; }
public Marble? Next { get; set; } public Marble Next { get; set; }
} }
public class MarbleGame public class MarbleGame
{ {
private Dictionary<long, long> Scores { get; } = new(); public Dictionary<long, long> Scores { get; } = new();
private Marble? _firstMarble; private Marble _firstMarble;
private Marble? _currentMarble; private Marble _currentMarble;
private long _currentPlayer; private long _currentPlayer;
private const long PointValueMultiple = 23; private const long PointValueMultiple = 23;
@@ -119,34 +119,20 @@ public class Day09 : IDay
Marble newMarble = new() { Value = i + 1 }; Marble newMarble = new() { Value = i + 1 };
if ((newMarble.Value % PointValueMultiple) > 0) if ((newMarble.Value % PointValueMultiple) > 0)
{ {
Marble? previousMarble = _currentMarble?.Next; Marble previousMarble = _currentMarble.Next;
Marble? nextMarble = previousMarble?.Next; Marble nextMarble = previousMarble.Next;
newMarble.Previous = previousMarble; newMarble.Previous = previousMarble;
newMarble.Next = nextMarble; newMarble.Next = nextMarble;
if(previousMarble != null)
{
previousMarble.Next = newMarble; previousMarble.Next = newMarble;
}
if(nextMarble != null)
{
nextMarble.Previous = newMarble; nextMarble.Previous = newMarble;
}
_currentMarble = newMarble; _currentMarble = newMarble;
} }
else else
{ {
Marble? marbleToRemove = _currentMarble?.Previous?.Previous?.Previous?.Previous?.Previous?.Previous?.Previous; Marble marbleToRemove = _currentMarble.Previous.Previous.Previous.Previous.Previous.Previous.Previous;
_currentMarble = marbleToRemove?.Next; _currentMarble = marbleToRemove.Next;
if (marbleToRemove == null) { continue; }
if(marbleToRemove.Previous != null)
{
marbleToRemove.Previous.Next = marbleToRemove.Next; marbleToRemove.Previous.Next = marbleToRemove.Next;
}
if (marbleToRemove.Next != null)
{
marbleToRemove.Next.Previous = marbleToRemove.Previous; marbleToRemove.Next.Previous = marbleToRemove.Previous;
}
long currentPlayerScore = Scores[_currentPlayer] + (newMarble.Value + marbleToRemove.Value); long currentPlayerScore = Scores[_currentPlayer] + (newMarble.Value + marbleToRemove.Value);
Scores[_currentPlayer] = currentPlayerScore; Scores[_currentPlayer] = currentPlayerScore;
@@ -155,17 +141,22 @@ public class Day09 : IDay
} }
} }
private void PrintStatus() public void PrintStatus()
{ {
Console.Write("[{0}] ", _currentPlayer); Console.Write("[{0}] ", _currentPlayer);
Marble? marble = _firstMarble; Marble marble = _firstMarble;
do do
{ {
Console.Write(_currentMarble?.Value == marble?.Value if (_currentMarble.Value == marble.Value)
? "({0}) " {
: "{0} ", marble?.Value); Console.Write("({0}) ", marble.Value);
marble = marble?.Next; }
} while (marble != null && marble.Value != 0); else
{
Console.Write("{0} ", marble.Value);
}
marble = marble.Next;
} while (marble.Value != 0);
Console.WriteLine(); Console.WriteLine();
} }

View File

@@ -156,13 +156,13 @@ Impressed by your sub-hour communication capabilities, the Elves are curious: ex
public class Day10 : IDay public class Day10 : IDay
{ {
public int Width { get; init; } = 65; public int Width { get; set; } = 65;
public int Height { get; init; } = 12; public int Height { get; set; } = 12;
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
LightField lightField = new(inputs); LightField lightField = new(inputs);
int t = lightField.SearchSmallerBoundingBox(); int t = lightField.SearchSmallerBoundindBox();
string result = lightField.Render(t, Width, Height); string result = lightField.Render(t, Width, Height);
return result; return result;
} }
@@ -170,20 +170,20 @@ public class Day10 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
LightField lightField = new(inputs); LightField lightField = new(inputs);
int t = lightField.SearchSmallerBoundingBox(); int t = lightField.SearchSmallerBoundindBox();
return t.ToString(); return t.ToString();
} }
public class LightPoint public class LightPoint
{ {
private int X { get; init; } public int X { get; set; }
private int Y { get; init; } public int Y { get; set; }
private int VX { get; init; } public int VX { get; set; }
private int VY { get; init; } public int VY { get; set; }
public static LightPoint FromString(string strPoint) public static LightPoint FromString(string strPoint)
{ {
string[] parts = strPoint.Split(["position=<", " ", ",", "> velocity=<", ">"], StringSplitOptions.RemoveEmptyEntries); string[] parts = strPoint.Split(new[] { "position=<", " ", ",", "> velocity=<", ">" }, StringSplitOptions.RemoveEmptyEntries);
LightPoint point = new() { LightPoint point = new() {
X = Convert.ToInt32(parts[0]), X = Convert.ToInt32(parts[0]),
Y = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[1]),
@@ -204,11 +204,16 @@ public class Day10 : IDay
} }
} }
private class LightField(string[] strPoints) public class LightField
{ {
private readonly List<LightPoint> _points = strPoints.Select(LightPoint.FromString).ToList(); private readonly List<LightPoint> _points;
public int SearchSmallerBoundingBox() public LightField(string[] strPoints)
{
_points = strPoints.Select(strPoint => LightPoint.FromString(strPoint)).ToList();
}
public int SearchSmallerBoundindBox()
{ {
int minHeight = int.MaxValue; int minHeight = int.MaxValue;
int minT = 0; int minT = 0;
@@ -283,7 +288,14 @@ public class Day10 : IDay
sb.AppendLine(); sb.AppendLine();
for (int i = 0; i < width; i++) for (int i = 0; i < width; i++)
{ {
sb.Append(field[i, j] > 0 ? "#" : "."); if (field[i, j] > 0)
{
sb.Append("#");
}
else
{
sb.Append(".");
}
} }
} }
return sb.ToString(); return sb.ToString();

View File

@@ -190,7 +190,7 @@ public class Day11 : IDay
return powerLevel; return powerLevel;
} }
private static void SearchBestRegion(int width, int height, int serial, out int x, out int y, out int size) public static void SearchBestRegion(int width, int height, int serial, out int x, out int y, out int size)
{ {
int[,] summationFiled = GenerateSumationField(width, height, serial); int[,] summationFiled = GenerateSumationField(width, height, serial);
int bestPowerLevel = int.MinValue; int bestPowerLevel = int.MinValue;

View File

@@ -96,23 +96,23 @@ public class Day12 : IDay
private class PlantRule private class PlantRule
{ {
public bool Minus2 { get; init; } public bool Minus2 { get; set; }
public bool Minus1 { get; init; } public bool Minus1 { get; set; }
public bool Current { get; init; } public bool Current { get; set; }
public bool Plus1 { get; init; } public bool Plus1 { get; set; }
public bool Plus2 { get; init; } public bool Plus2 { get; set; }
public bool Result { get; init; } public bool Result { get; set; }
} }
private const int SideMargin = 5; private const int SideMargin = 5;
private const int SideProcessMargin = 2; private const int SideProcessMargin = 2;
private readonly List<bool> _initialState = []; private List<bool> _initialState = new();
private readonly List<PlantRule> _rules = []; private List<PlantRule> _rules = new();
private long _offsetField; private long _offsetField;
private bool[] _field = []; private bool[] _field;
private bool[] _workField = []; private bool[] _workField;
private void Initialize(string[] inputs) private void Initialize(string[] inputs)
{ {
@@ -126,8 +126,9 @@ public class Day12 : IDay
for (int i = 2; i < inputs.Length; i++) for (int i = 2; i < inputs.Length; i++)
{ {
if (string.IsNullOrEmpty(inputs[i])) { continue; } if (string.IsNullOrEmpty(inputs[i])) { continue; }
string[] parts = inputs[i].Split([" => "], StringSplitOptions.RemoveEmptyEntries); string[] parts = inputs[i].Split(new[] { " => " }, StringSplitOptions.RemoveEmptyEntries);
_rules.Add(new PlantRule { _rules.Add(new PlantRule
{
Minus2 = (parts[0][0] == '#'), Minus2 = (parts[0][0] == '#'),
Minus1 = (parts[0][1] == '#'), Minus1 = (parts[0][1] == '#'),
Current = (parts[0][2] == '#'), Current = (parts[0][2] == '#'),
@@ -150,7 +151,9 @@ public class Day12 : IDay
private void SwapFields() private void SwapFields()
{ {
(_field, _workField) = (_workField, _field); bool[] aux = _field;
_field = _workField;
_workField = aux;
} }
private void RecenterField() private void RecenterField()
@@ -233,7 +236,8 @@ public class Day12 : IDay
rule.Minus1 == minus1 && rule.Minus1 == minus1 &&
rule.Current == current && rule.Current == current &&
rule.Plus1 == plus1 && rule.Plus1 == plus1 &&
rule.Plus2 == plus2 rule.Plus2 == plus2 &&
true
) )
{ {
result = rule.Result; result = rule.Result;

View File

@@ -217,7 +217,7 @@ public class Day13 : IDay
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
Initialize(inputs); Initialize(inputs);
Train? collidingTrain; Train collidingTrain;
do do
{ {
if (ShowProgress) { ShowGrid(); } if (ShowProgress) { ShowGrid(); }
@@ -229,7 +229,7 @@ public class Day13 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
Initialize(inputs); Initialize(inputs);
Train? lastCart; Train lastCart;
do do
{ {
if (ShowProgress) { ShowGrid(); } if (ShowProgress) { ShowGrid(); }
@@ -371,8 +371,8 @@ public class Day13 : IDay
private int _width; private int _width;
private int _height; private int _height;
private char[,] _grid = new char[0, 0]; private char[,] _grid;
private readonly List<Train> _trains = []; private List<Train> _trains = new();
private void Initialize(string[] inputs) private void Initialize(string[] inputs)
{ {
@@ -387,7 +387,8 @@ public class Day13 : IDay
char cell = inputs[j][i]; char cell = inputs[j][i];
if (cell == '^') if (cell == '^')
{ {
_trains.Add(new Train { _trains.Add(new Train
{
X = i, X = i,
Y = j, Y = j,
Direction = TrainDirection.North, Direction = TrainDirection.North,
@@ -397,7 +398,8 @@ public class Day13 : IDay
} }
if (cell == 'v') if (cell == 'v')
{ {
_trains.Add(new Train { _trains.Add(new Train
{
X = i, X = i,
Y = j, Y = j,
Direction = TrainDirection.South, Direction = TrainDirection.South,
@@ -407,7 +409,8 @@ public class Day13 : IDay
} }
if (cell == '<') if (cell == '<')
{ {
_trains.Add(new Train { _trains.Add(new Train
{
X = i, X = i,
Y = j, Y = j,
Direction = TrainDirection.West, Direction = TrainDirection.West,
@@ -417,7 +420,8 @@ public class Day13 : IDay
} }
if (cell == '>') if (cell == '>')
{ {
_trains.Add(new Train { _trains.Add(new Train
{
X = i, X = i,
Y = j, Y = j,
Direction = TrainDirection.East, Direction = TrainDirection.East,
@@ -430,9 +434,9 @@ public class Day13 : IDay
} }
} }
private Train? SimulateForFirstCollision() private Train SimulateForFirstCollision()
{ {
Train? collidingTrain = null; Train collidingTrain = null;
IEnumerable<Train> orderedTrains = _trains.OrderBy(t => t.X + (t.Y * _width)); IEnumerable<Train> orderedTrains = _trains.OrderBy(t => t.X + (t.Y * _width));
foreach (Train t in orderedTrains) foreach (Train t in orderedTrains)
{ {
@@ -443,13 +447,13 @@ public class Day13 : IDay
return collidingTrain; return collidingTrain;
} }
private Train? SimulateForLastCart() private Train SimulateForLastCart()
{ {
List<Train> orderedTrains = _trains.OrderBy(t => t.X + (t.Y * _width)).ToList(); List<Train> orderedTrains = _trains.OrderBy(t => t.X + (t.Y * _width)).ToList();
foreach (Train t in orderedTrains) foreach (Train t in orderedTrains)
{ {
t.Simulate(_grid); t.Simulate(_grid);
Train? collidingTrain = _trains.FirstOrDefault(x => x.X == t.X && x.Y == t.Y && t != x); Train collidingTrain = _trains.FirstOrDefault(x => x.X == t.X && x.Y == t.Y && t != x);
if (collidingTrain != null) if (collidingTrain != null)
{ {
_trains.Remove(t); _trains.Remove(t);
@@ -470,7 +474,7 @@ public class Day13 : IDay
{ {
for (int i = 0; i < _width; i++) for (int i = 0; i < _width; i++)
{ {
Train? t = _trains.FirstOrDefault(x => x.X == i && x.Y == j); Train t = _trains.FirstOrDefault(x => x.X == i && x.Y == j);
if (t != null) if (t != null)
{ {
if (t.Direction == TrainDirection.North) if (t.Direction == TrainDirection.North)
@@ -498,4 +502,5 @@ public class Day13 : IDay
Console.WriteLine(); Console.WriteLine();
} }
} }
} }

View File

@@ -62,7 +62,7 @@ public class Day14 : IDay
{ {
private long _numRecipes; private long _numRecipes;
private long _numRecipesAllocated; private long _numRecipesAllocated;
private byte[] _recipes = []; private byte[] _recipes;
private long _idxA; private long _idxA;
private long _idxB; private long _idxB;
private long _searchSkip; private long _searchSkip;

View File

@@ -377,18 +377,18 @@ public class Day15 : IDay
{ {
public enum EntityType { Elf, Goblin, } public enum EntityType { Elf, Goblin, }
private bool Show { get; set; } = false; public bool Show { get; set; } = false;
public class Entity public class Entity
{ {
private const int GoblinAttackPower = 3; public const int GoblinAttackPower = 3;
public static int ElfAttackPower { get; set; } = 3; public static int ElfAttackPower { get; set; } = 3;
private const int InitialHealth = 200; public const int InitialHealth = 200;
public EntityType Type { get; init; } public EntityType Type { get; set; }
public int X { get; set; } public int X { get; set; }
public int Y { get; set; } public int Y { get; set; }
public int Health { get; private set; } = InitialHealth; public int Health { get; set; } = InitialHealth;
public bool IsAlive() public bool IsAlive()
{ {
@@ -401,7 +401,8 @@ public class Day15 : IDay
(other.X + 1 == X && other.Y == Y) || (other.X + 1 == X && other.Y == Y) ||
(other.X - 1 == X && other.Y == Y) || (other.X - 1 == X && other.Y == Y) ||
(other.X == X && other.Y + 1 == Y) || (other.X == X && other.Y + 1 == Y) ||
(other.X == X && other.Y - 1 == Y) (other.X == X && other.Y - 1 == Y) ||
false
) )
{ {
return true; return true;
@@ -411,7 +412,7 @@ public class Day15 : IDay
public void Attack(char[,] map, Entity other) public void Attack(char[,] map, Entity other)
{ {
if (Type == EntityType.Elf) if(Type == EntityType.Elf)
{ {
other.Health -= ElfAttackPower; other.Health -= ElfAttackPower;
} }
@@ -434,19 +435,20 @@ public class Day15 : IDay
} }
} }
private class Target public class Target
{ {
public int X { get; init; } public int X { get; set; }
public int Y { get; init; } public int Y { get; set; }
public int Distance { get; set; } public int Distance { get; set; }
public int Priority { get; init; } public int Priority { get; set; }
public Entity Entity { get; set; }
} }
private int _width; private int _width;
private int _height; private int _height;
private char[,] _map = new char[0, 0]; private char[,] _map;
private readonly List<Entity> _entities = []; private List<Entity> _entities;
private BreadthFirstSearchGrid? _search; private BreadthFirstSearchGrid _search;
private int _rounds; private int _rounds;
private void Init(string[] inputs) private void Init(string[] inputs)
@@ -454,7 +456,7 @@ public class Day15 : IDay
_height = inputs.Length; _height = inputs.Length;
_width = inputs.Max(input => input.Length); _width = inputs.Max(input => input.Length);
_map = new char[_width, _height]; _map = new char[_width, _height];
_entities.Clear(); _entities = new List<Entity>();
for (int j = 0; j < _height; j++) for (int j = 0; j < _height; j++)
{ {
for (int i = 0; i < _width; i++) for (int i = 0; i < _width; i++)
@@ -471,7 +473,8 @@ public class Day15 : IDay
} }
else if (cell == 'E') else if (cell == 'E')
{ {
_entities.Add(new Entity { _entities.Add(new Entity
{
Type = EntityType.Elf, Type = EntityType.Elf,
X = i, X = i,
Y = j, Y = j,
@@ -480,7 +483,8 @@ public class Day15 : IDay
} }
else if (cell == 'G') else if (cell == 'G')
{ {
_entities.Add(new Entity { _entities.Add(new Entity
{
Type = EntityType.Goblin, Type = EntityType.Goblin,
X = i, X = i,
Y = j, Y = j,
@@ -501,7 +505,7 @@ public class Day15 : IDay
.ThenBy(e => e.X); .ThenBy(e => e.X);
} }
private IEnumerable<Entity> GetTargetEntities(Entity entity) public IEnumerable<Entity> GetTargetEntities(Entity entity)
{ {
return _entities return _entities
.Where(e => e.IsAlive() && e.Type != entity.Type) .Where(e => e.IsAlive() && e.Type != entity.Type)
@@ -509,29 +513,30 @@ public class Day15 : IDay
.ThenBy(e => e.X); .ThenBy(e => e.X);
} }
private Entity? GetBestInRangeTarget(Entity entity, IEnumerable<Entity> targets) public Entity GetBestInRangeTarget(Entity entity, IEnumerable<Entity> targets)
{ {
return targets return targets
.Where(entity.InRangeOf) .Where(e => entity.InRangeOf(e))
.OrderBy(e => e.Health) .OrderBy(e => e.Health)
.ThenBy(e => e.Y) .ThenBy(e => e.Y)
.ThenBy(e => e.X) .ThenBy(e => e.X)
.FirstOrDefault(); .FirstOrDefault();
} }
private void AddTarget(List<Target> targets, int targetX, int targetY, int priority) private void AddTarget(List<Target> targets, int targetX, int targetY, int priority, Entity entity)
{ {
if (_search == null) { return;}
if (targetX >= 0 && targetX < _width && targetY >= 0 && targetY < _height && _map[targetX, targetY] == '.') if (targetX >= 0 && targetX < _width && targetY >= 0 && targetY < _height && _map[targetX, targetY] == '.')
{ {
int distance = _search.QueryDistance(targetX, targetY); int distance = _search.QueryDistance(targetX, targetY);
if (distance >= 0) if (distance >= 0)
{ {
targets.Add(new Target { targets.Add(new Target
{
X = targetX, X = targetX,
Y = targetY, Y = targetY,
Distance = distance, Distance = distance,
Priority = priority, Priority = priority,
Entity = entity,
}); });
} }
} }
@@ -539,7 +544,6 @@ public class Day15 : IDay
private void RunBattle() private void RunBattle()
{ {
if (_search == null) { return;}
_rounds = 0; _rounds = 0;
bool running = true; bool running = true;
do do
@@ -548,7 +552,7 @@ public class Day15 : IDay
foreach (Entity entity in entities) foreach (Entity entity in entities)
{ {
if (entity.IsAlive() == false) { continue; } if (entity.IsAlive() == false) { continue; }
IEnumerable<Entity> entitiesTargets = GetTargetEntities(entity).ToList(); IEnumerable<Entity> entitiesTargets = GetTargetEntities(entity);
if (entitiesTargets.Any() == false) if (entitiesTargets.Any() == false)
{ {
running = false; running = false;
@@ -556,7 +560,7 @@ public class Day15 : IDay
} }
// Attack // Attack
Entity? targetInRange = GetBestInRangeTarget(entity, entitiesTargets); Entity targetInRange = GetBestInRangeTarget(entity, entitiesTargets);
if (targetInRange != null) if (targetInRange != null)
{ {
entity.Attack(_map, targetInRange); entity.Attack(_map, targetInRange);
@@ -569,18 +573,19 @@ public class Day15 : IDay
int priority = 0; int priority = 0;
foreach (Entity entityTarget in entitiesTargets) foreach (Entity entityTarget in entitiesTargets)
{ {
AddTarget(targets, entityTarget.X, entityTarget.Y - 1, priority++); AddTarget(targets, entityTarget.X, entityTarget.Y - 1, priority++, entityTarget);
AddTarget(targets, entityTarget.X - 1, entityTarget.Y, priority++); AddTarget(targets, entityTarget.X - 1, entityTarget.Y, priority++, entityTarget);
AddTarget(targets, entityTarget.X + 1, entityTarget.Y, priority++); AddTarget(targets, entityTarget.X + 1, entityTarget.Y, priority++, entityTarget);
AddTarget(targets, entityTarget.X, entityTarget.Y + 1, priority++); AddTarget(targets, entityTarget.X, entityTarget.Y + 1, priority++, entityTarget);
} }
Target? bestTarget = targets.OrderBy(t => t.Distance).ThenBy(t => t.Priority).FirstOrDefault(); Target bestTarget = targets.OrderBy(t => t.Distance).ThenBy(t => t.Priority).FirstOrDefault();
if (bestTarget != null) if (bestTarget != null)
{ {
_search.SearchCharGrid(_map, '.', bestTarget.X, bestTarget.Y); _search.SearchCharGrid(_map, '.', bestTarget.X, bestTarget.Y);
targets.Clear(); targets.Clear();
Target dirTarget;
Target dirTarget = new() { X = entity.X, Y = entity.Y - 1, Priority = 0, }; dirTarget = new Target { X = entity.X, Y = entity.Y - 1, Priority = 0, };
dirTarget.Distance = _search.QueryDistance(dirTarget.X, dirTarget.Y); dirTarget.Distance = _search.QueryDistance(dirTarget.X, dirTarget.Y);
if (dirTarget.Distance >= 0) targets.Add(dirTarget); if (dirTarget.Distance >= 0) targets.Add(dirTarget);
@@ -596,7 +601,7 @@ public class Day15 : IDay
dirTarget.Distance = _search.QueryDistance(dirTarget.X, dirTarget.Y); dirTarget.Distance = _search.QueryDistance(dirTarget.X, dirTarget.Y);
if (dirTarget.Distance >= 0) targets.Add(dirTarget); if (dirTarget.Distance >= 0) targets.Add(dirTarget);
Target? finalTarget = targets Target finalTarget = targets
.OrderBy(t => t.Distance) .OrderBy(t => t.Distance)
.ThenBy(t => t.Priority) .ThenBy(t => t.Priority)
.FirstOrDefault(); .FirstOrDefault();
@@ -608,17 +613,17 @@ public class Day15 : IDay
entity.MoveTo(_map, finalTarget.X, finalTarget.Y); entity.MoveTo(_map, finalTarget.X, finalTarget.Y);
// Attack // Attack
Entity? targetInRangeAfterMove = GetBestInRangeTarget(entity, entitiesTargets); Entity targetInRangeAfterMove = GetBestInRangeTarget(entity, entitiesTargets);
if (targetInRangeAfterMove != null) if (targetInRangeAfterMove != null)
{ {
entity.Attack(_map, targetInRangeAfterMove); entity.Attack(_map, targetInRangeAfterMove);
} }
} }
} }
if (running == false) { break; } if(running == false) { break; }
_rounds++; _rounds++;
if (Show) { PrintBattlefield(); } if (Show) { PrintBattlefield(); }
} while (true); } while (running);
if (Show) { PrintBattlefield(); } if (Show) { PrintBattlefield(); }
} }
@@ -632,8 +637,7 @@ public class Day15 : IDay
{ {
Console.Write(_map[i, j]); Console.Write(_map[i, j]);
} }
int j1 = j; IEnumerable<Entity> entitiesOnLine = _entities.Where(e => e.IsAlive() && e.Y == j).OrderBy(e => e.X);
IEnumerable<Entity> entitiesOnLine = _entities.Where(e => e.IsAlive() && e.Y == j1).OrderBy(e => e.X);
foreach (Entity entity in entitiesOnLine) foreach (Entity entity in entitiesOnLine)
{ {
Console.Write(" {0}({1})", (entity.Type == EntityType.Elf) ? 'E' : 'G', entity.Health); Console.Write(" {0}({1})", (entity.Type == EntityType.Elf) ? 'E' : 'G', entity.Health);
@@ -679,9 +683,10 @@ public class Day15 : IDay
private class BFSCell private class BFSCell
{ {
public bool Visited { get; set; } public bool Visited { get; set; }
public BFSCell CameFrom { get; set; }
public int Distance { get; set; } = -1; public int Distance { get; set; } = -1;
public int X { get; init; } public int X { get; set; }
public int Y { get; init; } public int Y { get; set; }
} }
private readonly BFSCell[,] _grid; private readonly BFSCell[,] _grid;
@@ -702,23 +707,24 @@ public class Day15 : IDay
} }
} }
private void Reset() public void Reset()
{ {
for (int j = 0; j < _height; j++) for(int j =0;j< _height; j++)
{ {
for (int i = 0; i < _width; i++) for(int i = 0; i < _width; i++)
{ {
BFSCell cell = _grid[i, j]; BFSCell cell = _grid[i, j];
cell.Visited = false; cell.Visited = false;
cell.CameFrom = null;
cell.Distance = -1; cell.Distance = -1;
} }
} }
} }
private void ProcessCell(char[,] grid, char empty, Queue<BFSCell> frontier, BFSCell? current, int nextX, int nextY) private void ProcessCell(char[,] grid, char empty, Queue<BFSCell> frontier, BFSCell current, int nextX, int nextY)
{ {
if (nextX < 0 || nextX >= _width || nextY < 0 || nextY >= _height) { return; } if (nextX < 0 || nextX >= _width || nextY < 0 || nextY >= _height) { return; }
if (grid[nextX, nextY] == empty || current == null) if (grid[nextX, nextY] == empty || current== null)
{ {
BFSCell cell = _grid[nextX, nextY]; BFSCell cell = _grid[nextX, nextY];
if (cell.Visited == false) if (cell.Visited == false)
@@ -726,6 +732,7 @@ public class Day15 : IDay
frontier.Enqueue(cell); frontier.Enqueue(cell);
cell.Visited = true; cell.Visited = true;
cell.Distance = (current?.Distance ?? -1) + 1; cell.Distance = (current?.Distance ?? -1) + 1;
cell.CameFrom = current;
} }
} }
} }

View File

@@ -87,8 +87,8 @@ public class Day16 : IDay
int count = 0; int count = 0;
int i = 0; int i = 0;
bool end = false; bool end = false;
int[]? beforeRegisters = null; int[] beforeRegisters = null;
int[]? instruction = null; int[] instruction = null;
const string beforeKeyword = "Before: ["; const string beforeKeyword = "Before: [";
const string afterKeyword = "After: ["; const string afterKeyword = "After: [";
while (inputs.Length > i) while (inputs.Length > i)
@@ -160,11 +160,17 @@ public class Day16 : IDay
private readonly List<ChronoInstruction> _instructions; private readonly List<ChronoInstruction> _instructions;
private class ChronoInstruction(string opName, Action<int, int, int> opFunc) private class ChronoInstruction
{ {
public int OpCode { get; set; } = -1; public int OpCode { get; set; } = -1;
public string OpName { get; } = opName; public string OpName { get; }
public Action<int, int, int> OpFunc { get; } = opFunc; public Action<int, int, int> OpFunc { get; }
public ChronoInstruction(string opName, Action<int, int, int> opFunc)
{
OpName = opName;
OpFunc = opFunc;
}
public Dictionary<int, int> OpCodeHistogram { get; } = new(); public Dictionary<int, int> OpCodeHistogram { get; } = new();
@@ -185,7 +191,7 @@ public class Day16 : IDay
public ChronoMachine() public ChronoMachine()
{ {
_registers = new int[4]; _registers = new int[4];
_instructions = [ _instructions = new List<ChronoInstruction> {
new("addr", Op_AddR), new("addr", Op_AddR),
new("addi", Op_AddI), new("addi", Op_AddI),
new("mulr", Op_MulR), new("mulr", Op_MulR),
@@ -202,7 +208,7 @@ public class Day16 : IDay
new("eqir", Op_EqIR), new("eqir", Op_EqIR),
new("eqri", Op_EqRI), new("eqri", Op_EqRI),
new("eqrr", Op_EqRR), new("eqrr", Op_EqRR),
]; };
} }
public void ResetRegisters() public void ResetRegisters()
@@ -335,7 +341,7 @@ public class Day16 : IDay
public void InitOpCodes(bool debug = false) public void InitOpCodes(bool debug = false)
{ {
if (debug) if(debug)
{ {
foreach (ChronoInstruction instruction in _instructions) foreach (ChronoInstruction instruction in _instructions)
{ {
@@ -368,7 +374,7 @@ public class Day16 : IDay
instruction.OpCode = opCode; instruction.OpCode = opCode;
_dictInstructions.Add(opCode, instruction); _dictInstructions.Add(opCode, instruction);
if (debug) { Console.WriteLine($"{instruction.OpName}: {instruction.OpCode}"); } if(debug) { Console.WriteLine($"{instruction.OpName}: {instruction.OpCode}"); }
} }
} }
} }

View File

@@ -68,8 +68,8 @@ public class Day23 : IDay
public string ResolvePart1(string[] inputs) public string ResolvePart1(string[] inputs)
{ {
List<NanoBot> nanoBots = NanoBot.ListFromStrings(inputs); List<NanoBot> nanoBots = NanoBot.ListFromStrings(inputs);
NanoBot? bestNanoBot = nanoBots.OrderBy(nanoBot => nanoBot.Range).LastOrDefault(); NanoBot bestNanoBot = nanoBots.OrderBy(nanoBot => nanoBot.Range).LastOrDefault();
int countInRange = nanoBots.Count(nanoBot => bestNanoBot?.InRange(nanoBot) == true); int countInRange = nanoBots.Where(nanoBot => bestNanoBot.InRange(nanoBot)).Count();
return countInRange.ToString(); return countInRange.ToString();
} }
@@ -82,7 +82,7 @@ public class Day23 : IDay
long minX = long.MaxValue; long minX = long.MaxValue;
long minY = long.MaxValue; long minY = long.MaxValue;
long minZ = long.MaxValue; long minZ = long.MaxValue;
foreach (NanoBot nanoBot in nanoBots) foreach(NanoBot nanoBot in nanoBots)
{ {
if (nanoBot.X < minX) { minX = nanoBot.X; } if (nanoBot.X < minX) { minX = nanoBot.X; }
if (nanoBot.X > maxX) { maxX = nanoBot.X; } if (nanoBot.X > maxX) { maxX = nanoBot.X; }
@@ -112,11 +112,11 @@ public class Day23 : IDay
for (long i = minX; i <= maxX; i += scale) for (long i = minX; i <= maxX; i += scale)
{ {
int count = 0; int count = 0;
foreach (NanoBot nanoBot in nanoBots) foreach(NanoBot nanoBot in nanoBots)
{ {
if (nanoBot.InRange(i, j, k, scale)) { count++; } if (nanoBot.InRange(i, j, k, scale)) { count++; }
} }
if (count > bestCount) if(count> bestCount)
{ {
bestX = i; bestX = i;
bestY = j; bestY = j;
@@ -134,7 +134,7 @@ public class Day23 : IDay
minZ = bestZ - scale; minZ = bestZ - scale;
maxZ = bestZ + scale; maxZ = bestZ + scale;
if (scale == 1) if(scale == 1)
{ {
long distance = bestX + bestY + bestZ; long distance = bestX + bestY + bestZ;
return distance.ToString(); return distance.ToString();
@@ -145,14 +145,14 @@ public class Day23 : IDay
public class NanoBot public class NanoBot
{ {
public long X { get; private init; } public long X { get; set; }
public long Y { get; private init; } public long Y { get; set; }
public long Z { get; private init; } public long Z { get; set; }
public long Range { get; private init; } public long Range { get; set; }
private static NanoBot? FromString(string strInput) public static NanoBot FromString(string strInput)
{ {
string[] parts = strInput.Split(["pos=<", ",", ">, r="], StringSplitOptions.RemoveEmptyEntries); string[] parts = strInput.Split(new[] { "pos=<", ",", ">, r=", }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 4) { return null; } if (parts.Length != 4) { return null; }
NanoBot nanoBot = new() { NanoBot nanoBot = new() {
X = Convert.ToInt64(parts[0]), X = Convert.ToInt64(parts[0]),
@@ -166,18 +166,18 @@ public class Day23 : IDay
public static List<NanoBot> ListFromStrings(string[] inputs) public static List<NanoBot> ListFromStrings(string[] inputs)
{ {
List<NanoBot> nanoBots = inputs List<NanoBot> nanoBots = inputs
.Select(FromString) .Select(strInput => FromString(strInput))
.OfType<NanoBot>() .Where(nanoBot => nanoBot != null)
.ToList(); .ToList();
return nanoBots; return nanoBots;
} }
private long ManhattanDistance(NanoBot other) public long ManhattanDistance(NanoBot other)
{ {
return ManhattanDistance(other.X, other.Y, other.Z); return ManhattanDistance(other.X, other.Y, other.Z);
} }
private long ManhattanDistance(long x, long y, long z) public long ManhattanDistance(long x, long y, long z)
{ {
long distance = Math.Abs(X - x) + Math.Abs(Y - y) + Math.Abs(Z - z); long distance = Math.Abs(X - x) + Math.Abs(Y - y) + Math.Abs(Z - z);
return distance; return distance;

View File

@@ -1,18 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2020.Tests</RootNamespace> <RootNamespace>AdventOfCode2020.Tests</RootNamespace>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.3"/> <PackageReference Include="xunit" Version="2.6.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.5"> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -20,7 +18,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode2020\AdventOfCode2020.csproj"/> <ProjectReference Include="..\AdventOfCode2020\AdventOfCode2020.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -7,16 +7,16 @@ public class Day01_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day01 day = new(); var day = new Day01();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"1721", "1721",
"979", "979",
"366", "366",
"299", "299",
"675", "675",
"1456", "1456",
]); });
Assert.Equal("514579", result); Assert.Equal("514579", result);
} }
@@ -28,16 +28,16 @@ public class Day01_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day01 day = new(); var day = new Day01();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"1721", "1721",
"979", "979",
"366", "366",
"299", "299",
"675", "675",
"1456", "1456",
]); });
Assert.Equal("241861950", result); Assert.Equal("241861950", result);
} }

View File

@@ -7,13 +7,13 @@ public class Day02_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day02 day = new(); var day = new Day02();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"1-3 a: abcde", "1-3 a: abcde",
"1-3 b: cdefg", "1-3 b: cdefg",
"2-9 c: ccccccccc", "2-9 c: ccccccccc",
]); });
Assert.Equal("2", result); Assert.Equal("2", result);
} }
@@ -25,13 +25,13 @@ public class Day02_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day02 day = new(); var day = new Day02();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"1-3 a: abcde", "1-3 a: abcde",
"1-3 b: cdefg", "1-3 b: cdefg",
"2-9 c: ccccccccc", "2-9 c: ccccccccc",
]); });
Assert.Equal("1", result); Assert.Equal("1", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day03_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day03 day = new(); var day = new Day03();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"..##.......", "..##.......",
"#...#...#..", "#...#...#..",
".#....#..#.", ".#....#..#.",
@@ -19,7 +19,7 @@ public class Day03_Tests
"#.##...#...", "#.##...#...",
"#...##....#", "#...##....#",
".#..#...#.#", ".#..#...#.#",
]); });
Assert.Equal("7", result); Assert.Equal("7", result);
} }
@@ -27,9 +27,9 @@ public class Day03_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day03 day = new(); var day = new Day03();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"..##.......", "..##.......",
"#...#...#..", "#...#...#..",
".#....#..#.", ".#....#..#.",
@@ -41,7 +41,7 @@ public class Day03_Tests
"#.##...#...", "#.##...#...",
"#...##....#", "#...##....#",
".#..#...#.#", ".#..#...#.#",
]); });
Assert.Equal("336", result); Assert.Equal("336", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day04_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day04 day = new(); var day = new Day04();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"ecl:gry pid:860033327 eyr:2020 hcl:#fffffd", "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd",
"byr:1937 iyr:2017 cid:147 hgt:183cm", "byr:1937 iyr:2017 cid:147 hgt:183cm",
"", "",
@@ -21,7 +21,7 @@ public class Day04_Tests
"", "",
"hcl:#cfa07d eyr:2025 pid:166559648", "hcl:#cfa07d eyr:2025 pid:166559648",
"iyr:2011 ecl:brn hgt:59in", "iyr:2011 ecl:brn hgt:59in",
]); });
Assert.Equal("2", result); Assert.Equal("2", result);
} }
@@ -29,9 +29,9 @@ public class Day04_Tests
[Fact] [Fact]
public void ResolvePart2__ExampleInvalid() public void ResolvePart2__ExampleInvalid()
{ {
Day04 day = new(); var day = new Day04();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"eyr:1972 cid:100", "eyr:1972 cid:100",
"hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926", "hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926",
"", "",
@@ -45,7 +45,7 @@ public class Day04_Tests
"hgt:59cm ecl:zzz", "hgt:59cm ecl:zzz",
"eyr:2038 hcl:74454a iyr:2023", "eyr:2038 hcl:74454a iyr:2023",
"pid:3556412378 byr:2007", "pid:3556412378 byr:2007",
]); });
Assert.Equal("0", result); Assert.Equal("0", result);
} }
@@ -53,9 +53,9 @@ public class Day04_Tests
[Fact] [Fact]
public void ResolvePart2__ExampleValid() public void ResolvePart2__ExampleValid()
{ {
Day04 day = new(); var day = new Day04();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980", "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980",
"hcl:#623a2f", "hcl:#623a2f",
"", "",
@@ -68,7 +68,7 @@ public class Day04_Tests
"eyr:2022", "eyr:2022",
"", "",
"iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719", "iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719",
]); });
Assert.Equal("4", result); Assert.Equal("4", result);
} }

View File

@@ -5,11 +5,11 @@ public class Day05_Tests
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()
{ {
Day05 day = new(); var day = new Day05();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"FBFBBFFRLR", "FBFBBFFRLR",
]); });
Assert.Equal("357", result); Assert.Equal("357", result);
} }
@@ -17,11 +17,11 @@ public class Day05_Tests
[Fact] [Fact]
public void ResolvePart1__Example2() public void ResolvePart1__Example2()
{ {
Day05 day = new(); var day = new Day05();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"BFFFBBFRRR", "BFFFBBFRRR",
]); });
Assert.Equal("567", result); Assert.Equal("567", result);
} }
@@ -29,11 +29,11 @@ public class Day05_Tests
[Fact] [Fact]
public void ResolvePart1__Example3() public void ResolvePart1__Example3()
{ {
Day05 day = new(); var day = new Day05();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"FFFBBBFRRR", "FFFBBBFRRR",
]); });
Assert.Equal("119", result); Assert.Equal("119", result);
} }
@@ -41,11 +41,11 @@ public class Day05_Tests
[Fact] [Fact]
public void ResolvePart1__Example4() public void ResolvePart1__Example4()
{ {
Day05 day = new(); var day = new Day05();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"BBFFBBFRLL", "BBFFBBFRLL",
]); });
Assert.Equal("820", result); Assert.Equal("820", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day06_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day06 day = new(); var day = new Day06();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"abc", "abc",
"", "",
"a", "a",
@@ -23,7 +23,7 @@ public class Day06_Tests
"a", "a",
"", "",
"b", "b",
]); });
Assert.Equal("11", result); Assert.Equal("11", result);
} }
@@ -31,9 +31,9 @@ public class Day06_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day06 day = new(); var day = new Day06();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"abc", "abc",
"", "",
"a", "a",
@@ -49,7 +49,7 @@ public class Day06_Tests
"a", "a",
"", "",
"b", "b",
]); });
Assert.Equal("6", result); Assert.Equal("6", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day07_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day07 day = new(); var day = new Day07();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"light red bags contain 1 bright white bag, 2 muted yellow bags.", "light red bags contain 1 bright white bag, 2 muted yellow bags.",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags.", "dark orange bags contain 3 bright white bags, 4 muted yellow bags.",
"bright white bags contain 1 shiny gold bag.", "bright white bags contain 1 shiny gold bag.",
@@ -17,7 +17,7 @@ public class Day07_Tests
"vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.", "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.",
"faded blue bags contain no other bags.", "faded blue bags contain no other bags.",
"dotted black bags contain no other bags.", "dotted black bags contain no other bags.",
]); });
Assert.Equal("4", result); Assert.Equal("4", result);
} }
@@ -25,9 +25,9 @@ public class Day07_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day07 day = new(); var day = new Day07();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"shiny gold bags contain 2 dark red bags.", "shiny gold bags contain 2 dark red bags.",
"dark red bags contain 2 dark orange bags.", "dark red bags contain 2 dark orange bags.",
"dark orange bags contain 2 dark yellow bags.", "dark orange bags contain 2 dark yellow bags.",
@@ -35,7 +35,7 @@ public class Day07_Tests
"dark green bags contain 2 dark blue bags.", "dark green bags contain 2 dark blue bags.",
"dark blue bags contain 2 dark violet bags.", "dark blue bags contain 2 dark violet bags.",
"dark violet bags contain no other bags.", "dark violet bags contain no other bags.",
]); });
Assert.Equal("126", result); Assert.Equal("126", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day08_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day08 day = new(); var day = new Day08();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"nop +0", "nop +0",
"acc +1", "acc +1",
"jmp +4", "jmp +4",
@@ -17,7 +17,7 @@ public class Day08_Tests
"acc +1", "acc +1",
"jmp -4", "jmp -4",
"acc +6", "acc +6",
]); });
Assert.Equal("5", result); Assert.Equal("5", result);
} }
@@ -25,9 +25,9 @@ public class Day08_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day08 day = new(); var day = new Day08();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"nop +0", "nop +0",
"acc +1", "acc +1",
"jmp +4", "jmp +4",
@@ -37,7 +37,7 @@ public class Day08_Tests
"acc +1", "acc +1",
"jmp -4", "jmp -4",
"acc +6", "acc +6",
]); });
Assert.Equal("8", result); Assert.Equal("8", result);
} }

View File

@@ -5,9 +5,9 @@ public class Day09_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day09 day = new(); var day = new Day09();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"35", "35",
"20", "20",
"15", "15",
@@ -28,7 +28,7 @@ public class Day09_Tests
"277", "277",
"309", "309",
"576", "576",
]); });
Assert.Equal("127", result); Assert.Equal("127", result);
} }
@@ -36,9 +36,9 @@ public class Day09_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day09 day = new(); var day = new Day09();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"35", "35",
"20", "20",
"15", "15",
@@ -59,7 +59,7 @@ public class Day09_Tests
"277", "277",
"309", "309",
"576", "576",
]); });
Assert.Equal("62", result); Assert.Equal("62", result);
} }

View File

@@ -2,9 +2,8 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2020</RootNamespace> <RootNamespace>AdventOfCode2020</RootNamespace>
</PropertyGroup> </PropertyGroup>
@@ -15,7 +14,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj"/> <ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -112,4 +112,5 @@ public class Day03 : IDay
} }
return treeCnt; return treeCnt;
} }
} }

View File

@@ -127,7 +127,7 @@ public class Day04 : IDay
{ {
List<Dictionary<string, string>> passports = Passports_Parse(inputs); List<Dictionary<string, string>> passports = Passports_Parse(inputs);
int cnt = 0; int cnt = 0;
List<string> neededFields = [ List<string> neededFields = new() {
"byr", // Birth Year "byr", // Birth Year
"iyr", // Issue Year "iyr", // Issue Year
"eyr", // Expiration Year "eyr", // Expiration Year
@@ -135,7 +135,7 @@ public class Day04 : IDay
"hcl", // Hair Color "hcl", // Hair Color
"ecl", // Eye Color "ecl", // Eye Color
"pid", // Passport ID "pid", // Passport ID
]; };
foreach (Dictionary<string, string> passport in passports) foreach (Dictionary<string, string> passport in passports)
{ {
@@ -167,7 +167,7 @@ public class Day04 : IDay
private List<Dictionary<string, string>> Passports_Parse(string[] inputs) private List<Dictionary<string, string>> Passports_Parse(string[] inputs)
{ {
List<Dictionary<string, string>> passports = []; List<Dictionary<string, string>> passports = new();
Dictionary<string, string> passport = new(); Dictionary<string, string> passport = new();
foreach (string input in inputs) foreach (string input in inputs)
{ {
@@ -257,4 +257,5 @@ public class Day04 : IDay
if (input.All(char.IsNumber) == false) { return null; } if (input.All(char.IsNumber) == false) { return null; }
return Convert.ToInt32(input); return Convert.ToInt32(input);
} }
} }

View File

@@ -64,7 +64,7 @@ public class Day05 : IDay
int maxSerialNumber = 0; int maxSerialNumber = 0;
foreach (string input in inputs) foreach (string input in inputs)
{ {
Seat? seat = Seat_Parse(input); Seat seat = Seat_Parse(input);
if (seat == null) { continue; } if (seat == null) { continue; }
int newSerialNumber = seat.GetSerialNumber(); int newSerialNumber = seat.GetSerialNumber();
if (newSerialNumber > maxSerialNumber) { maxSerialNumber = newSerialNumber; } if (newSerialNumber > maxSerialNumber) { maxSerialNumber = newSerialNumber; }
@@ -83,7 +83,7 @@ public class Day05 : IDay
} }
foreach (string input in inputs) foreach (string input in inputs)
{ {
Seat? seat = Seat_Parse(input); Seat seat = Seat_Parse(input);
if (seat == null) { continue; } if (seat == null) { continue; }
seats[seat.Column][seat.Row] = 'X'; seats[seat.Column][seat.Row] = 'X';
@@ -166,11 +166,11 @@ public class Day05 : IDay
} }
} }
private Seat? Seat_Parse(string input) private Seat Seat_Parse(string input)
{ {
if (input.Length != 10 || if (input.Length != 10 ||
input.All(c => c == 'F' || c == 'B' || c == 'L' || c == 'R') == false input.All(c => c == 'F' || c == 'B' || c == 'L' || c == 'R') == false ||
) false)
{ {
return null; return null;
} }

View File

@@ -67,7 +67,10 @@ public class Day06 : IDay
foreach (char c in input) foreach (char c in input)
{ {
groupMap.TryAdd(c, true); if (groupMap.ContainsKey(c) == false)
{
groupMap.Add(c, true);
}
} }
} }
if (groupMap.Count > 0) if (groupMap.Count > 0)
@@ -75,7 +78,7 @@ public class Day06 : IDay
groupMaps.Add(groupMap); groupMaps.Add(groupMap);
} }
int total = groupMaps.Sum(dict => dict.Count); int total = groupMaps.Sum(groupMap => groupMap.Count);
return total.ToString(); return total.ToString();
} }
@@ -98,9 +101,13 @@ public class Day06 : IDay
groupCount++; groupCount++;
foreach (char c in input) foreach (char c in input)
{ {
if (groupMap.TryAdd(c, 1) == false) if (groupMap.ContainsKey(c) == false)
{ {
groupMap[c] += 1; groupMap.Add(c, 1);
}
else
{
groupMap[c] = groupMap[c] + 1;
} }
} }
} }

View File

@@ -72,15 +72,15 @@ public class Day07 : IDay
{ {
string myBagColor = "shiny gold"; string myBagColor = "shiny gold";
List<BaggageRule> rules = []; List<BaggageRule> rules = new();
foreach (string input in inputs) foreach (string input in inputs)
{ {
BaggageRule rule = BaggageRule_Parse(input); BaggageRule rule = BaggageRule_Parse(input);
rules.Add(rule); rules.Add(rule);
} }
List<string> bagColorsToCheck = [myBagColor]; List<string> bagColorsToCheck = new() { myBagColor };
List<string> bagColorsChecked = [myBagColor]; List<string> bagColorsChecked = new() { myBagColor };
int cntBagColors = 0; int cntBagColors = 0;
while (bagColorsToCheck.Count > 0) while (bagColorsToCheck.Count > 0)
{ {
@@ -108,7 +108,7 @@ public class Day07 : IDay
{ {
string myBagColor = "shiny gold"; string myBagColor = "shiny gold";
List<BaggageRule> rules = []; List<BaggageRule> rules = new();
foreach (string input in inputs) foreach (string input in inputs)
{ {
BaggageRule rule = BaggageRule_Parse(input); BaggageRule rule = BaggageRule_Parse(input);
@@ -116,30 +116,31 @@ public class Day07 : IDay
} }
Dictionary<string, BaggageRule> dictRules = rules.ToDictionary(x => x.BagColor); Dictionary<string, BaggageRule> dictRules = rules.ToDictionary(x => x.BagColor);
int cnt = BaggageRule_CountChildren(myBagColor, dictRules); int cnt = BaggageRule_CountChilds(myBagColor, dictRules);
return cnt.ToString(); return cnt.ToString();
} }
private class BaggageContainRule public class BaggageContainRule
{ {
public string BagColor { get; set; } = string.Empty; public string BagColor { get; set; }
public int Count { get; init; } public int Count { get; set; }
} }
private class BaggageRule public class BaggageRule
{ {
public string BagColor { get; set; } = string.Empty; public string BagColor { get; set; }
public List<BaggageContainRule> Contain { get; } = []; public List<BaggageContainRule> Contain { get; set; }
} }
private BaggageRule BaggageRule_Parse(string input) public BaggageRule BaggageRule_Parse(string input)
{ {
string[] words = input.Split(' '); string[] words = input.Split(' ');
string status = "Parse Color 1"; string status = "Parse Color 1";
BaggageRule rule = new(); BaggageRule rule = new();
BaggageContainRule? containRule = null; rule.Contain = new List<BaggageContainRule>();
BaggageContainRule containRule = null;
string color1 = string.Empty; string color1 = string.Empty;
foreach (string word in words) foreach (string word in words)
@@ -163,14 +164,9 @@ public class Day07 : IDay
status = "Parse Contain count"; status = "Parse Contain count";
break; break;
case "Parse Contain count": case "Parse Contain count":
if (word == "no") if (word == "no") { status = "End"; break; }
{ containRule = new BaggageContainRule();
status = "End"; containRule.Count = Convert.ToInt32(word);
break;
}
containRule = new BaggageContainRule {
Count = Convert.ToInt32(word),
};
status = "Parse Contain color 1"; status = "Parse Contain color 1";
break; break;
case "Parse Contain color 1": case "Parse Contain color 1":
@@ -178,17 +174,12 @@ public class Day07 : IDay
status = "Parse Contain color 2"; status = "Parse Contain color 2";
break; break;
case "Parse Contain color 2": case "Parse Contain color 2":
if(containRule == null) { break; }
containRule.BagColor = string.Concat(color1, " ", word); containRule.BagColor = string.Concat(color1, " ", word);
rule.Contain.Add(containRule); rule.Contain.Add(containRule);
status = "Parse Contain continue"; status = "Parse Contain continue";
break; break;
case "Parse Contain continue": case "Parse Contain continue":
if (word == "bag," || word == "bags,") if (word == "bag," || word == "bags,") { status = "Parse Contain count"; break; }
{
status = "Parse Contain count";
break;
}
status = "End"; status = "End";
break; break;
case "End": case "End":
@@ -198,13 +189,13 @@ public class Day07 : IDay
return rule; return rule;
} }
private int BaggageRule_CountChildren(string color, Dictionary<string, BaggageRule> dictRules) public int BaggageRule_CountChilds(string color, Dictionary<string, BaggageRule> dictRules)
{ {
int cnt = 0; int cnt = 0;
BaggageRule rule = dictRules[color]; BaggageRule rule = dictRules[color];
foreach (BaggageContainRule containRule in rule.Contain) foreach (BaggageContainRule containRule in rule.Contain)
{ {
cnt += (BaggageRule_CountChildren(containRule.BagColor, dictRules) + 1) * containRule.Count; cnt += (BaggageRule_CountChilds(containRule.BagColor, dictRules) + 1) * containRule.Count;
} }
return cnt; return cnt;
} }

View File

@@ -124,14 +124,14 @@ public class Day08 : IDay
return vm.Accumulator.ToString(); return vm.Accumulator.ToString();
} }
private enum OpCode public enum OpCode
{ {
Acc, Acc,
Jmp, Jmp,
Nop, Nop,
} }
private class Instruction public class Instruction
{ {
public OpCode OpCode { get; set; } public OpCode OpCode { get; set; }
public int Value { get; set; } public int Value { get; set; }
@@ -154,9 +154,14 @@ public class Day08 : IDay
OpCode = OpCode.Nop; OpCode = OpCode.Nop;
} }
Value = Convert.ToInt32(parts[1].StartsWith("+") if (parts[1].StartsWith("+"))
? parts[1].Substring(1) {
: parts[1]); Value = Convert.ToInt32(parts[1].Substring(1));
}
else
{
Value = Convert.ToInt32(parts[1]);
}
Executed = false; Executed = false;
} }
} }
@@ -171,7 +176,7 @@ public class Day08 : IDay
public VM(string[] inputs) public VM(string[] inputs)
{ {
Instructions = []; Instructions = new List<Instruction>();
foreach (string input in inputs) foreach (string input in inputs)
{ {
Instructions.Add(new Instruction(input)); Instructions.Add(new Instruction(input));

View File

@@ -163,4 +163,5 @@ public class Day09 : IDay
return firstInvalid; return firstInvalid;
} }
} }

View File

@@ -1,18 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2023.Tests</RootNamespace> <RootNamespace>AdventOfCode2023.Tests</RootNamespace>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.3"/> <PackageReference Include="xunit" Version="2.6.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.5"> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -20,7 +19,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode2023\AdventOfCode2023.csproj"/> <ProjectReference Include="..\AdventOfCode2023\AdventOfCode2023.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -5,14 +5,14 @@ public class Day01_Tests
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
{ {
Day01 day = new(); var day = new Day01();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"1abc2", "1abc2",
"pqr3stu8vwx", "pqr3stu8vwx",
"a1b2c3d4e5f", "a1b2c3d4e5f",
"treb7uchet", "treb7uchet",
]); });
Assert.Equal("142", result); Assert.Equal("142", result);
} }
@@ -20,9 +20,9 @@ public class Day01_Tests
[Fact] [Fact]
public void ResolvePart2__Example() public void ResolvePart2__Example()
{ {
Day01 day = new(); var day = new Day01();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"two1nine", "two1nine",
"eightwothree", "eightwothree",
"abcone2threexyz", "abcone2threexyz",
@@ -30,7 +30,7 @@ public class Day01_Tests
"4nineeightseven2", "4nineeightseven2",
"zoneight234", "zoneight234",
"7pqrstsixteen", "7pqrstsixteen",
]); });
Assert.Equal("281", result); Assert.Equal("281", result);
} }

View File

@@ -41,13 +41,13 @@ public class Day02_Tests
{ {
Day02 day = new(); Day02 day = new();
string result = day.ResolvePart1([ string result = day.ResolvePart1(new[] {
"Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green", "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green",
"Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue", "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue",
"Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red", "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red",
"Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red", "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red",
"Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green", "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green",
]); });
Assert.Equal("8", result); Assert.Equal("8", result);
} }
@@ -57,13 +57,13 @@ public class Day02_Tests
{ {
Day02 day = new(); Day02 day = new();
string result = day.ResolvePart2([ string result = day.ResolvePart2(new[] {
"Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green", "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green",
"Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue", "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue",
"Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red", "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red",
"Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red", "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red",
"Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green", "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green",
]); });
Assert.Equal("2286", result); Assert.Equal("2286", result);
} }

View File

@@ -5,11 +5,11 @@ public class Day03_Tests
[Fact] [Fact]
public void SearchNextSchemaNumber__NoNumbers__Null() public void SearchNextSchemaNumber__NoNumbers__Null()
{ {
string[] inputs = [ string[] inputs = new[] {
"..........", "..........",
"..........", "..........",
"..........", "..........",
]; };
Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 0); Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 0);
Assert.Null(number); Assert.Null(number);
@@ -18,11 +18,11 @@ public class Day03_Tests
[Fact] [Fact]
public void SearchNextSchemaNumber__OneNumber__Valid() public void SearchNextSchemaNumber__OneNumber__Valid()
{ {
string[] inputs = [ string[] inputs = new[] {
"..........", "..........",
"....420...", "....420...",
"..........", "..........",
]; };
Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 0); Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 0);
Assert.NotNull(number); Assert.NotNull(number);
@@ -35,11 +35,11 @@ public class Day03_Tests
[Fact] [Fact]
public void SearchNextSchemaNumber__TwoNumbersSkipFirst__ValidSecond() public void SearchNextSchemaNumber__TwoNumbersSkipFirst__ValidSecond()
{ {
string[] inputs = [ string[] inputs = new[] {
"69........", "69........",
"....420...", "....420...",
"..........", "..........",
]; };
Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 4); Day03.SchemaNumber? number = Day03.SearchNextSchemaNumber(inputs, 0, 4);
Assert.NotNull(number); Assert.NotNull(number);
@@ -49,7 +49,7 @@ public class Day03_Tests
Assert.Equal(420, number.Value.Value); Assert.Equal(420, number.Value.Value);
} }
private string[] _example = [ private string[] _example = new[] {
"467..114..", "467..114..",
"...*......", "...*......",
"..35..633.", "..35..633.",
@@ -60,7 +60,7 @@ public class Day03_Tests
"......755.", "......755.",
"...$.*....", "...$.*....",
".664.598..", ".664.598..",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()

View File

@@ -2,14 +2,14 @@ namespace AdventOfCode2023.Tests;
public class Day04_Tests public class Day04_Tests
{ {
private readonly string[] _example = [ private readonly string[] _example = {
"Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53", "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 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 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 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 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", "Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()

View File

@@ -2,7 +2,7 @@ namespace AdventOfCode2023.Tests;
public class Day05_Tests public class Day05_Tests
{ {
private readonly string[] _example = [ private readonly string[] _example = {
"seeds: 79 14 55 13", "seeds: 79 14 55 13",
"", "",
"seed-to-soil map:", "seed-to-soil map:",
@@ -36,7 +36,7 @@ public class Day05_Tests
"humidity-to-location map:", "humidity-to-location map:",
"60 56 37", "60 56 37",
"56 93 4", "56 93 4",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()
@@ -61,7 +61,7 @@ public class Day05_Tests
[Fact] [Fact]
public void AlmanacMapping_ParseNext__Empty__Null() public void AlmanacMapping_ParseNext__Empty__Null()
{ {
Day05.LinesReader reader = new([]); Day05.LinesReader reader = new(Array.Empty<string>());
Day05.AlmanacMapping? mapping = Day05.AlmanacMapping.ParseNext(reader); Day05.AlmanacMapping? mapping = Day05.AlmanacMapping.ParseNext(reader);
Assert.Null(mapping); Assert.Null(mapping);
@@ -70,11 +70,11 @@ public class Day05_Tests
[Fact] [Fact]
public void AlmanacMapping_ParseNext__Example1() public void AlmanacMapping_ParseNext__Example1()
{ {
Day05.LinesReader reader = new([ Day05.LinesReader reader = new(new[] {
"seed-to-soil map:", "seed-to-soil map:",
"50 98 2", "50 98 2",
"52 50 48", "52 50 48",
]); });
Day05.AlmanacMapping? mapping = Day05.AlmanacMapping.ParseNext(reader); Day05.AlmanacMapping? mapping = Day05.AlmanacMapping.ParseNext(reader);
Assert.NotNull(mapping); Assert.NotNull(mapping);

View File

@@ -2,10 +2,10 @@ namespace AdventOfCode2023.Tests;
public class Day06_Tests public class Day06_Tests
{ {
private readonly string[] _example = [ private readonly string[] _example = {
"Time: 7 15 30", "Time: 7 15 30",
"Distance: 9 40 200", "Distance: 9 40 200",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()

View File

@@ -2,13 +2,13 @@ namespace AdventOfCode2023.Tests;
public class Day07_Tests public class Day07_Tests
{ {
private readonly string[] _example = [ private readonly string[] _example = {
"32T3K 765", "32T3K 765",
"T55J5 684", "T55J5 684",
"KK677 28", "KK677 28",
"KTJJT 220", "KTJJT 220",
"QQQJA 483", "QQQJA 483",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()

View File

@@ -2,7 +2,7 @@ namespace AdventOfCode2023.Tests;
public class Day08_Tests public class Day08_Tests
{ {
private readonly string[] _example1 = [ private readonly string[] _example1 = {
"RL", "RL",
"", "",
"AAA = (BBB, CCC)", "AAA = (BBB, CCC)",
@@ -12,7 +12,7 @@ public class Day08_Tests
"EEE = (EEE, EEE)", "EEE = (EEE, EEE)",
"GGG = (GGG, GGG)", "GGG = (GGG, GGG)",
"ZZZ = (ZZZ, ZZZ)", "ZZZ = (ZZZ, ZZZ)",
]; };
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()
@@ -24,13 +24,13 @@ public class Day08_Tests
Assert.Equal("2", result); Assert.Equal("2", result);
} }
private readonly string[] _example2 = [ private readonly string[] _example2 = {
"LLR", "LLR",
"", "",
"AAA = (BBB, BBB)", "AAA = (BBB, BBB)",
"BBB = (AAA, ZZZ)", "BBB = (AAA, ZZZ)",
"ZZZ = (ZZZ, ZZZ)", "ZZZ = (ZZZ, ZZZ)",
]; };
[Fact] [Fact]
public void ResolvePart1__Example2() public void ResolvePart1__Example2()
@@ -42,7 +42,7 @@ public class Day08_Tests
Assert.Equal("6", result); Assert.Equal("6", result);
} }
private readonly string[] _example3 = [ private readonly string[] _example3 = {
"LR", "LR",
"", "",
"11A = (11B, XXX)", "11A = (11B, XXX)",
@@ -53,7 +53,7 @@ public class Day08_Tests
"22C = (22Z, 22Z)", "22C = (22Z, 22Z)",
"22Z = (22B, 22B)", "22Z = (22B, 22B)",
"XXX = (XXX, XXX)", "XXX = (XXX, XXX)",
]; };
[Fact] [Fact]
public void ResolvePart2__Example3() public void ResolvePart2__Example3()
@@ -64,4 +64,5 @@ public class Day08_Tests
Assert.Equal("6", result); Assert.Equal("6", result);
} }
} }

View File

@@ -2,11 +2,11 @@ namespace AdventOfCode2023.Tests;
public class Day09_Tests public class Day09_Tests
{ {
private readonly string[] _example = [ private readonly string[] _example = {
"0 3 6 9 12 15", "0 3 6 9 12 15",
"1 3 6 10 15 21", "1 3 6 10 15 21",
"10 13 16 21 30 45", "10 13 16 21 30 45",
]; };
[Fact] [Fact]
public void ResolvePart1__Example() public void ResolvePart1__Example()

View File

@@ -2,13 +2,13 @@ namespace AdventOfCode2023.Tests;
public class Day10_Tests public class Day10_Tests
{ {
private readonly string[] _example1 = [ private readonly string[] _example1 = {
"7-F7-", "7-F7-",
".FJ|7", ".FJ|7",
"SJLL7", "SJLL7",
"|F--J", "|F--J",
"LJ.LJ", "LJ.LJ",
]; };
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()
@@ -20,7 +20,7 @@ public class Day10_Tests
Assert.Equal("8", result); Assert.Equal("8", result);
} }
private readonly string[] _example2 = [ private readonly string[] _example2 = {
"...........", "...........",
".S-------7.", ".S-------7.",
".|F-----7|.", ".|F-----7|.",
@@ -30,7 +30,7 @@ public class Day10_Tests
".|..|.|..|.", ".|..|.|..|.",
".L--J.L--J.", ".L--J.L--J.",
"...........", "...........",
]; };
[Fact] [Fact]
public void ResolvePart2__Example2() public void ResolvePart2__Example2()
@@ -43,7 +43,7 @@ public class Day10_Tests
} }
private readonly string[] _example3 = [ private readonly string[] _example3 = {
"FF7FSF7F7F7F7F7F---7", "FF7FSF7F7F7F7F7F---7",
"L|LJ||||||||||||F--J", "L|LJ||||||||||||F--J",
"FL-7LJLJ||||||LJL-77", "FL-7LJLJ||||||LJL-77",
@@ -54,7 +54,7 @@ public class Day10_Tests
"7-L-JL7||F7|L7F-7F7|", "7-L-JL7||F7|L7F-7F7|",
"L.L7LFJ|||||FJL7||LJ", "L.L7LFJ|||||FJL7||LJ",
"L7JLJL-JLJLJL--JLJ.L", "L7JLJL-JLJLJL--JLJ.L",
]; };
[Fact] [Fact]
public void ResolvePart2__Example3() public void ResolvePart2__Example3()

View File

@@ -2,7 +2,7 @@ namespace AdventOfCode2023.Tests;
public class Day11_Tests public class Day11_Tests
{ {
private readonly string[] _example1 = [ private readonly string[] _example1 = {
"...#......", "...#......",
".......#..", ".......#..",
"#.........", "#.........",
@@ -13,7 +13,7 @@ public class Day11_Tests
"..........", "..........",
".......#..", ".......#..",
"#...#.....", "#...#.....",
]; };
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()
@@ -24,4 +24,5 @@ public class Day11_Tests
Assert.Equal("374", result); Assert.Equal("374", result);
} }
} }

View File

@@ -2,14 +2,14 @@ namespace AdventOfCode2023.Tests;
public class Day12_Tests public class Day12_Tests
{ {
private readonly string[] _example1 = [ private readonly string[] _example1 = {
"???.### 1,1,3", "???.### 1,1,3",
".??..??...?##. 1,1,3", ".??..??...?##. 1,1,3",
"?#?#?#?#?#?#?#? 1,3,1,6", "?#?#?#?#?#?#?#? 1,3,1,6",
"????.#...#... 4,1,1", "????.#...#... 4,1,1",
"????.######..#####. 1,6,5", "????.######..#####. 1,6,5",
"?###???????? 3,2,1", "?###???????? 3,2,1",
]; };
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()

View File

@@ -10,13 +10,13 @@ namespace AdventOfCode2023.Tests;
public class Day24_Tests public class Day24_Tests
{ {
private string[] _example1 = [ private readonly string[] _example1 = {
"19, 13, 30 @ -2, 1, -2", "19, 13, 30 @ -2, 1, -2",
"18, 19, 22 @ -1, -1, -2", "18, 19, 22 @ -1, -1, -2",
"20, 25, 34 @ -2, -2, -4", "20, 25, 34 @ -2, -2, -4",
"12, 31, 28 @ -1, -2, -1", "12, 31, 28 @ -1, -2, -1",
"20, 19, 15 @ 1, -5, -3", "20, 19, 15 @ 1, -5, -3",
]; };
[Fact] [Fact]
public void ResolvePart1__Example1() public void ResolvePart1__Example1()
@@ -28,6 +28,35 @@ public class Day24_Tests
Assert.Equal("2", result); Assert.Equal("2", result);
} }
[Fact]
public void ResolvePart2__Example1()
{
Day24 day = new();
string result = day.ResolvePart2(_example1);
Assert.Equal("47", result);
}
private readonly string[] _example2 = {
"19, 13, 30 @ -2, 1, -2",
"18, 19, 22 @ -1, -1, -2",
"20, 25, 34 @ -2, -2, -4",
"12, 31, 28 @ -1, -2, -1",
"20, 19, 15 @ 1, -5, -3",
"24, 13, 10 @ -3, 1, 2",
};
[Fact]
public void ResolvePart2__Example2()
{
Day24 day = new();
string result = day.ResolvePart2(_example2);
Assert.Equal("47", result);
}
[Fact] [Fact]
public void Hail_Intersect2D__Examples1() public void Hail_Intersect2D__Examples1()
{ {
@@ -37,34 +66,66 @@ public class Day24_Tests
Day24.Hail hailD = new("12, 31, 28 @ -1, -2, -1"); Day24.Hail hailD = new("12, 31, 28 @ -1, -2, -1");
Day24.Hail hailE = new("20, 19, 15 @ 1, -5, -3"); Day24.Hail hailE = new("20, 19, 15 @ 1, -5, -3");
(bool intersect_A_B, _, _, _) = hailA.Intersect2D(hailB); (bool intersect_A_B, _, _) = hailA.Intersect2D(hailB);
Assert.True(intersect_A_B); Assert.True(intersect_A_B);
(bool intersect_A_C, _, _, _) = hailA.Intersect2D(hailC); (bool intersect_A_C, _, _) = hailA.Intersect2D(hailC);
Assert.True(intersect_A_C); Assert.True(intersect_A_C);
(bool intersect_A_D, _, _, _) = hailA.Intersect2D(hailD); (bool intersect_A_D, _, _) = hailA.Intersect2D(hailD);
Assert.True(intersect_A_D); Assert.True(intersect_A_D);
(bool intersect_A_E, _, _, _) = hailA.Intersect2D(hailE); (bool intersect_A_E, _, _) = hailA.Intersect2D(hailE);
Assert.True(intersect_A_E); Assert.True(intersect_A_E);
(bool intersect_B_C, _, _, _) = hailB.Intersect2D(hailC); (bool intersect_B_C, _, _) = hailB.Intersect2D(hailC);
Assert.False(intersect_B_C); Assert.False(intersect_B_C);
(bool intersect_B_D, _, _, _) = hailB.Intersect2D(hailD); (bool intersect_B_D, _, _) = hailB.Intersect2D(hailD);
Assert.True(intersect_B_D); Assert.True(intersect_B_D);
(bool intersect_B_E, _, _, _) = hailB.Intersect2D(hailE); (bool intersect_B_E, _, _) = hailB.Intersect2D(hailE);
Assert.True(intersect_B_E); Assert.True(intersect_B_E);
(bool intersect_C_D, _, _, _) = hailC.Intersect2D(hailD); (bool intersect_C_D, _, _) = hailC.Intersect2D(hailD);
Assert.True(intersect_C_D); Assert.True(intersect_C_D);
(bool intersect_C_E, _, _, _) = hailC.Intersect2D(hailE); (bool intersect_C_E, _, _) = hailC.Intersect2D(hailE);
Assert.True(intersect_C_E); Assert.True(intersect_C_E);
(bool intersect_D_E, _, _, _) = hailD.Intersect2D(hailE); (bool intersect_D_E, _, _) = hailD.Intersect2D(hailE);
Assert.True(intersect_D_E); Assert.True(intersect_D_E);
} }
[Fact]
public void Hail_Intersect3D__Examples1()
{
Day24.Hail rock = new("24, 13, 10 @ -3, 1, 2");
Day24.Hail hailA = new("19, 13, 30 @ -2, 1, -2");
Day24.Hail hailB = new("18, 19, 22 @ -1, -1, -2");
Day24.Hail hailC = new("20, 25, 34 @ -2, -2, -4");
Day24.Hail hailD = new("12, 31, 28 @ -1, -2, -1");
Day24.Hail hailE = new("20, 19, 15 @ 1, -5, -3");
(bool intersect_A, double t_A, _) = rock.Intersect3D(hailA);
Assert.True(intersect_A);
Assert.Equal(5, t_A);
(bool intersect_B, double t_B, _) = rock.Intersect3D(hailB);
Assert.True(intersect_B);
Assert.Equal(3, t_B);
(bool intersect_C, double t_C, _) = rock.Intersect3D(hailC);
Assert.True(intersect_C);
Assert.Equal(4, t_C);
(bool intersect_D, double t_D, _) = rock.Intersect3D(hailD);
Assert.True(intersect_D);
Assert.Equal(6, t_D);
(bool intersect_E, double t_E, _) = rock.Intersect3D(hailE);
Assert.True(intersect_E);
Assert.Equal(1, t_E);
}
} }

View File

@@ -2,10 +2,10 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2023</RootNamespace> <RootNamespace>AdventOfCode2023</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -15,7 +15,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj"/> <ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -78,7 +78,7 @@ public class Day01 : IDay
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
List<(string Text, int Value)> digits = [ List<(string Text, int Value)> digits = new() {
("1", 1), ("1", 1),
("2", 2), ("2", 2),
("3", 3), ("3", 3),
@@ -97,7 +97,7 @@ public class Day01 : IDay
("seven", 7), ("seven", 7),
("eight", 8), ("eight", 8),
("nine", 9), ("nine", 9),
]; };
int sum = 0; int sum = 0;
foreach (string line in inputs) foreach (string line in inputs)

View File

@@ -115,11 +115,11 @@ public class Day03 : IDay
public struct SchemaNumber public struct SchemaNumber
{ {
public string[] Schema { get; init; } public string[] Schema { get; set; }
public int Row { get; init; } public int Row { get; set; }
public int Column { get; init; } public int Column { get; set; }
public int Lenght { get; init; } public int Lenght { get; set; }
public int Value { get; init; } public int Value { get; set; }
} }
public static SchemaNumber? SearchNextSchemaNumber(string[] schema, int initialRow, int initialColumn) public static SchemaNumber? SearchNextSchemaNumber(string[] schema, int initialRow, int initialColumn)
@@ -191,4 +191,5 @@ public class Day03 : IDay
return false; return false;
} }
} }

View File

@@ -135,5 +135,6 @@ public class Day04 : IDay
{ {
return _myNumbers.Count(myNumber => _winningNumbers.Contains(myNumber)); return _myNumbers.Count(myNumber => _winningNumbers.Contains(myNumber));
} }
} }
} }

View File

@@ -136,7 +136,7 @@ public class Day05 : IDay
LinesReader reader = new(inputs); LinesReader reader = new(inputs);
Almanac? almanac = Almanac.Parse(reader); Almanac? almanac = Almanac.Parse(reader);
int i = 0; int i = 0;
List<AlmanacRangeMapping> ranges = []; List<AlmanacRangeMapping> ranges = new();
while (almanac?.Seeds.Count > i) while (almanac?.Seeds.Count > i)
{ {
long seed = almanac.Seeds[i]; long seed = almanac.Seeds[i];
@@ -155,14 +155,21 @@ public class Day05 : IDay
} }
public class LinesReader(string[] lines) public class LinesReader
{ {
private readonly string[] _lines;
private int _index; private int _index;
public LinesReader(string[] lines)
{
_lines = lines;
_index = 0;
}
public string? GetLine() public string? GetLine()
{ {
if (_index >= lines.Length) { return null; } if (_index >= _lines.Length) { return null; }
string line = lines[_index]; string line = _lines[_index];
_index++; _index++;
return line; return line;
} }
@@ -291,7 +298,7 @@ public class Day05 : IDay
{ {
public string Name { get; private init; } = string.Empty; public string Name { get; private init; } = string.Empty;
public List<AlmanacRangeMapping> RangeMappings { get; } = []; public List<AlmanacRangeMapping> RangeMappings { get; } = new();
public static AlmanacMapping? ParseNext(LinesReader reader) public static AlmanacMapping? ParseNext(LinesReader reader)
{ {
@@ -339,32 +346,29 @@ public class Day05 : IDay
public List<AlmanacRangeMapping> Apply(AlmanacRangeMapping range) public List<AlmanacRangeMapping> Apply(AlmanacRangeMapping range)
{ {
List<AlmanacRangeMapping> unMappedRanges = [ List<AlmanacRangeMapping> unMappedRanges = new() {
range, range,
]; };
List<AlmanacRangeMapping> newUnMappedRanges = []; List<AlmanacRangeMapping> newUnMappedRanges = new();
List<AlmanacRangeMapping> mappedRanges = []; List<AlmanacRangeMapping> mappedRanges = new();
int i = 0; int i = 0;
while (RangeMappings.Count > i) while (RangeMappings.Count > i)
{ {
AlmanacRangeMapping rangeMapping = RangeMappings[i]; AlmanacRangeMapping rangeMapping = RangeMappings[i];
foreach (AlmanacRangeMapping unMappedRange in unMappedRanges) for (int j = 0; j < unMappedRanges.Count; j++)
{ {
AlmanacRangeMapping.ClipResult result = rangeMapping.Clip(unMappedRange); AlmanacRangeMapping.ClipResult result = rangeMapping.Clip(unMappedRanges[j]);
if (result.Clipped != null) { mappedRanges.Add(result.Clipped.Value); } if (result.Clipped != null) { mappedRanges.Add(result.Clipped.Value); }
if (result.PreClip != null) { newUnMappedRanges.Add(result.PreClip.Value); } if (result.PreClip != null) { newUnMappedRanges.Add(result.PreClip.Value); }
if (result.PostClip != null) { newUnMappedRanges.Add(result.PostClip.Value); } if (result.PostClip != null) { newUnMappedRanges.Add(result.PostClip.Value); }
} }
unMappedRanges = newUnMappedRanges; unMappedRanges = newUnMappedRanges;
newUnMappedRanges = []; newUnMappedRanges = new List<AlmanacRangeMapping>();
i++; i++;
} }
List<AlmanacRangeMapping> resultMappedRanges = []; return mappedRanges.Union(unMappedRanges).ToList();
resultMappedRanges.AddRange(mappedRanges);
resultMappedRanges.AddRange(unMappedRanges);
return resultMappedRanges;
} }
} }
@@ -377,7 +381,7 @@ public class Day05 : IDay
public List<long> Seeds { get; } public List<long> Seeds { get; }
private List<AlmanacMapping> Mappings { get; } = []; private List<AlmanacMapping> Mappings { get; } = new();
public static Almanac? Parse(LinesReader reader) public static Almanac? Parse(LinesReader reader)
{ {

View File

@@ -114,9 +114,9 @@ public class Day07 : IDay
public class CamelCard public class CamelCard
{ {
private readonly static char[] Labels = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2']; private readonly static char[] Labels = { 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2' };
private readonly static char[] LabelsWithJoker = ['A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J']; private readonly static char[] LabelsWithJoker = { 'A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J' };
private const char JokerLabel = 'J'; private const char JokerLabel = 'J';
public enum Types public enum Types

View File

@@ -105,11 +105,18 @@ public class Day08 : IDay
return steps.ToString(); return steps.ToString();
} }
private class MapNode(string strMapNode) private class MapNode
{ {
public string Key { get; } = strMapNode.Substring(0, 3); public string Key { get; set; }
public string LeftKey { get; } = strMapNode.Substring(7, 3); public string LeftKey { get; set; }
public string RightKey { get; } = strMapNode.Substring(12, 3); public string RightKey { get; set; }
public MapNode(string strMapNode)
{
Key = strMapNode.Substring(0, 3);
LeftKey = strMapNode.Substring(7, 3);
RightKey = strMapNode.Substring(12, 3);
}
} }
private class Map private class Map
@@ -148,23 +155,32 @@ public class Day08 : IDay
} }
} }
private class MapWalker(Map map, string startKey) private class MapWalker
{ {
private MapNode _currentNode = map.GetByKey(startKey) ?? map.Nodes.First(); private readonly Map _map;
private MapNode _currentNode;
private long _steps; private long _steps;
public MapWalker(Map map, string startKey)
{
_map = map;
_currentNode = map.GetByKey(startKey) ?? map.Nodes.First();
_steps = 0;
}
public void StepWhile(Func<MapWalker, bool> condition) public void StepWhile(Func<MapWalker, bool> condition)
{ {
while (condition(this)) while (condition(this))
{ {
char leftRightInstruction = map.GetInstruction(_steps); char leftRightInstruction = _map.GetInstruction(_steps);
if (leftRightInstruction == 'L') if (leftRightInstruction == 'L')
{ {
_currentNode = map.GetByKey(_currentNode.LeftKey) ?? map.Nodes.First(); _currentNode = _map.GetByKey(_currentNode.LeftKey) ?? _map.Nodes.First();
} }
if (leftRightInstruction == 'R') if (leftRightInstruction == 'R')
{ {
_currentNode = map.GetByKey(_currentNode.RightKey) ?? map.Nodes.First(); _currentNode = _map.GetByKey(_currentNode.RightKey) ?? _map.Nodes.First();
} }
_steps++; _steps++;
} }

View File

@@ -167,12 +167,12 @@ public class Day09 : IDay
public long ExtrapolatePast() public long ExtrapolatePast()
{ {
_derivatives.Last().Insert(0, 0); _derivatives.Last().Insert(0,0);
for (int i = _derivatives.Count - 2; i >= 0; i--) for (int i = _derivatives.Count - 2; i >= 0; i--)
{ {
long firstDerivative1 = _derivatives[i].First(); long firstDerivative1 = _derivatives[i].First();
long firstDerivative0 = _derivatives[i + 1].First(); long firstDerivative0 = _derivatives[i + 1].First();
_derivatives[i].Insert(0, firstDerivative1 - firstDerivative0); _derivatives[i].Insert(0,firstDerivative1 - firstDerivative0);
} }
long firstNumber = _numbers.First(); long firstNumber = _numbers.First();
long firstDerivative = _derivatives[0].First(); long firstDerivative = _derivatives[0].First();

View File

@@ -228,10 +228,16 @@ public class Day10 : IDay
return countInside.ToString(); return countInside.ToString();
} }
private struct Point(int x, int y) private struct Point
{ {
public int X = x; public int X;
public int Y = y; public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
} }
private class PipeMaze private class PipeMaze
@@ -317,7 +323,7 @@ public class Day10 : IDay
x: point.X + 1, x: point.X + 1,
y: point.Y); y: point.Y);
} }
if (point.Y == prevPoint.Y && prevPoint.X > point.X) if(point.Y == prevPoint.Y && prevPoint.X > point.X)
{ {
return new Point( return new Point(
x: point.X, x: point.X,
@@ -333,7 +339,7 @@ public class Day10 : IDay
x: point.X - 1, x: point.X - 1,
y: point.Y); y: point.Y);
} }
if (point.Y == prevPoint.Y && prevPoint.X < point.X) if(point.Y == prevPoint.Y && prevPoint.X < point.X)
{ {
return new Point( return new Point(
x: point.X, x: point.X,
@@ -349,7 +355,7 @@ public class Day10 : IDay
x: point.X - 1, x: point.X - 1,
y: point.Y); y: point.Y);
} }
if (point.Y == prevPoint.Y && prevPoint.X < point.X) if(point.Y == prevPoint.Y && prevPoint.X < point.X)
{ {
return new Point( return new Point(
x: point.X, x: point.X,
@@ -365,7 +371,7 @@ public class Day10 : IDay
x: point.X + 1, x: point.X + 1,
y: point.Y); y: point.Y);
} }
if (point.Y == prevPoint.Y && prevPoint.X > point.X) if(point.Y == prevPoint.Y && prevPoint.X > point.X)
{ {
return new Point( return new Point(
x: point.X, x: point.X,
@@ -432,10 +438,10 @@ public class Day10 : IDay
private char CalculateCell(Point point) private char CalculateCell(Point point)
{ {
Point? pointRight = FollowPipe(new Point(point.X + 1, point.Y), point); Point? pointRight =FollowPipe(new Point(point.X + 1, point.Y), point);
Point? pointLeft = FollowPipe(new Point(point.X - 1, point.Y), point); Point? pointLeft =FollowPipe(new Point(point.X - 1, point.Y), point);
Point? pointDown = FollowPipe(new Point(point.X, point.Y + 1), point); Point? pointDown =FollowPipe(new Point(point.X, point.Y + 1), point);
Point? pointUp = FollowPipe(new Point(point.X, point.Y - 1), point); Point? pointUp =FollowPipe(new Point(point.X, point.Y - 1), point);
if (pointRight != null && pointLeft == null && pointDown != null && pointUp == null) if (pointRight != null && pointLeft == null && pointDown != null && pointUp == null)
{ {
return 'F'; return 'F';
@@ -501,12 +507,12 @@ public class Day10 : IDay
} }
else if (cell == 'J') else if (cell == 'J')
{ {
if (cellStart == 'F') if(cellStart == 'F')
{ {
inside = inside != true; inside = inside != true;
cellStart = null; cellStart = null;
} }
else if (cellStart == 'L') else if(cellStart == 'L')
{ {
cellStart = null; cellStart = null;
} }
@@ -517,23 +523,23 @@ public class Day10 : IDay
{ {
cellStart = 'F'; cellStart = 'F';
} }
else if (cellStart == 'J') else if(cellStart == 'J')
{ {
inside = inside != true; inside = inside != true;
cellStart = null; cellStart = null;
} }
else if (cellStart == '7') else if(cellStart == '7')
{ {
cellStart = null; cellStart = null;
} }
} }
else if (cell == '7') else if (cell == '7')
{ {
if (cellStart == 'F') if(cellStart == 'F')
{ {
cellStart = null; cellStart = null;
} }
else if (cellStart == 'L') else if(cellStart == 'L')
{ {
inside = inside != true; inside = inside != true;
cellStart = null; cellStart = null;
@@ -545,11 +551,11 @@ public class Day10 : IDay
{ {
cellStart = 'L'; cellStart = 'L';
} }
else if (cellStart == 'J') else if(cellStart == 'J')
{ {
cellStart = null; cellStart = null;
} }
else if (cellStart == '7') else if(cellStart == '7')
{ {
inside = inside != true; inside = inside != true;
cellStart = null; cellStart = null;

View File

@@ -130,8 +130,8 @@ public class Day11 : IDay
private struct Point private struct Point
{ {
public long X { get; init; } public long X { get; set; }
public long Y { get; init; } public long Y { get; set; }
} }
private class GalaxyMap private class GalaxyMap

View File

@@ -1,3 +1,4 @@
using System.Text;
namespace AdventOfCode2023; namespace AdventOfCode2023;

View File

@@ -72,6 +72,44 @@ However, you'll need to search a much larger test area if you want to see if any
Considering only the X and Y axes, check all pairs of hailstones' future paths for intersections. How many of these intersections occur within the test area? Considering only the X and Y axes, check all pairs of hailstones' future paths for intersections. How many of these intersections occur within the test area?
--- Part Two ---
Upon further analysis, it doesn't seem like any hailstones will naturally collide. It's up to you to fix that!
You find a rock on the ground nearby. While it seems extremely unlikely, if you throw it just right, you should be able to hit every hailstone in a single throw!
You can use the probably-magical winds to reach any integer position you like and to propel the rock at any integer velocity. Now including the Z axis in your calculations, if you throw the rock at time 0, where do you need to be so that the rock perfectly collides with every hailstone? Due to probably-magical inertia, the rock won't slow down or change direction when it collides with a hailstone.
In the example above, you can achieve this by moving to position 24, 13, 10 and throwing the rock at velocity -3, 1, 2. If you do this, you will hit every hailstone as follows:
Hailstone: 19, 13, 30 @ -2, 1, -2
Collision time: 5
Collision position: 9, 18, 20
Hailstone: 18, 19, 22 @ -1, -1, -2
Collision time: 3
Collision position: 15, 16, 16
Hailstone: 20, 25, 34 @ -2, -2, -4
Collision time: 4
Collision position: 12, 17, 18
Hailstone: 12, 31, 28 @ -1, -2, -1
Collision time: 6
Collision position: 6, 19, 22
Hailstone: 20, 19, 15 @ 1, -5, -3
Collision time: 1
Collision position: 21, 14, 12
Above, each hailstone is identified by its initial position and its velocity. Then, the time and position of that hailstone's collision with your rock are given.
After 1 nanosecond, the rock has exactly the same position as one of the hailstones, obliterating it into ice dust! Another hailstone is smashed to bits two nanoseconds after that. After a total of 6 nanoseconds, all of the hailstones have been destroyed.
So, at time 0, the rock needs to be at X position 24, Y position 13, and Z position 10. Adding these three coordinates together produces 47. (Don't add any coordinates from the rock's velocity.)
Determine the exact position and velocity the rock needs to have at time 0 so that it perfectly collides with every hailstone. What do you get if you add up the X, Y, and Z coordinates of that initial position?
*/ */
@@ -88,32 +126,257 @@ public class Day24 : IDay
{ {
for (int j = i + 1; j < hails.Length; j++) for (int j = i + 1; j < hails.Length; j++)
{ {
(bool intersects, double s, double t, Vector3D point) = hails[i].Intersect2D(hails[j]); (bool intersects, double s, double t) = hails[i].Intersect2D(hails[j]);
if (intersects && s > 0 && t > 0 && point.X >= min && point.X <= max && point.Y >= min && point.Y <= max) if (intersects && s > 0 && t > 0)
{
long x = (long)(hails[i].Position.X + t * hails[i].Velocity.X);
long y = (long)(hails[i].Position.Y + t * hails[i].Velocity.Y);
if (x >= min && x <= max && y >= min && y <= max)
{ {
count++; count++;
} }
} }
} }
}
return count.ToString(); return count.ToString();
} }
public string ResolvePart2(string[] inputs) public string ResolvePart2(string[] inputs)
{ {
throw new NotImplementedException(); string result = ResolvePart2_SolutionInDataSet(inputs);
if (string.IsNullOrEmpty(result) == false)
{
return result;
}
result = ResolvePart2_BruteForceXY(inputs);
if (string.IsNullOrEmpty(result) == false)
{
return result;
}
return string.Empty;
} }
public struct Vector3D(long x, long y, long z)
public string ResolvePart2_BruteForceXY(string[] inputs)
{ {
public readonly long X = x; Hail[] hails = inputs.Select(input => new Hail(input)).ToArray();
public readonly long Y = y;
public readonly long Z = z; // Brute force solution
long absMax = hails
.Select(h => new[] { h.Velocity.X, h.Velocity.Y, h.Velocity.Z, })
.SelectMany(x => x).Select(Math.Abs)
.Max();
Console.WriteLine($"Velocity AbsMax: {absMax}");
long minV = -absMax;
long maxV = absMax;
Vector3D? collisionPoint = null;
for (long vy = minV; vy < maxV && collisionPoint == null; vy++)
{
for (long vx = minV; vx < maxV && collisionPoint == null; vx++)
{
Vector3D newVelocity0 = new(
x: hails[0].Velocity.X - vx,
y: hails[0].Velocity.Y - vy,
z: hails[0].Velocity.Z);
Hail shiftedHail0 = new(hails[0].Position, newVelocity0);
Vector3D newVelocity1 = new(
x: hails[1].Velocity.X - vx,
y: hails[1].Velocity.Y - vy,
z: hails[1].Velocity.Z);
Hail shiftedHail1 = new(hails[1].Position, newVelocity1);
(bool intersects, double s, double t) = shiftedHail0.Intersect2D(shiftedHail1);
if (intersects == false || s < 0.0f || t < 0.0) { continue; }
long x = (long)(shiftedHail0.Position.X + t * shiftedHail0.Velocity.X);
long y = (long)(shiftedHail0.Position.Y + t * shiftedHail0.Velocity.Y);
Vector3D firstCollisionPoint = new(x, y, 0);
//Console.WriteLine($"Possible Rock: {vx} {vy} | {firstCollisionPoint.X}, {firstCollisionPoint.Y}, {firstCollisionPoint.Z} @ {vx}, {vy}, ?? | {s} {t}");
Hail[] shiftedHails = hails.Select(h =>
{
Vector3D newVelocity = new(
x: h.Velocity.X - vx,
y: h.Velocity.Y - vy,
z: h.Velocity.Z);
Hail newHail = new(h.Position, newVelocity);
return newHail;
}).ToArray();
Vector3D currentCollisionPoint = firstCollisionPoint;
bool allCollided = true;
for (int i = 2; i < shiftedHails.Length; i++)
{
(bool intersectsIter, double sIter, double tIter) = shiftedHails[0].Intersect2D(shiftedHails[i]);
long xIter = (long)(shiftedHail0.Position.X + tIter * shiftedHail0.Velocity.X);
long yIter = (long)(shiftedHail0.Position.Y + tIter * shiftedHail0.Velocity.Y);
Vector3D collisionPointIter = new(xIter, yIter, 0);
if (
intersectsIter &&
currentCollisionPoint.Cmp2D(collisionPointIter) &&
true)
{
continue;
}
allCollided = false;
//Console.WriteLine($"... Invalid rock: {i}");
break;
}
if (allCollided)
{
long xCollision = (long)(hails[0].Position.X + t * hails[0].Velocity.X);
long yCollision = (long)(hails[0].Position.Y + t * hails[0].Velocity.Y);
long zCollision = (long)(hails[0].Position.Z + t * hails[0].Velocity.Z);
Console.WriteLine($"Possible Rock: {xCollision}, {yCollision}, {zCollision} @ {vx}, {vy}, ?? | {t}");
collisionPoint = new Vector3D(xCollision, yCollision, zCollision);
}
}
}
if (collisionPoint == null)
{
return string.Empty;
}
return (collisionPoint.Value.X + collisionPoint.Value.Y + collisionPoint.Value.Z).ToString();
}
private string ResolvePart2_BruteForceXYZ(string[] inputs)
{
Hail[] hails = inputs.Select(input => new Hail(input)).ToArray();
// Brute force solution
long absMax = hails
.Select(h => new[] { h.Velocity.X, h.Velocity.Y, h.Velocity.Z, })
.SelectMany(x => x).Select(Math.Abs)
.Max();
Console.WriteLine($"Velocity AbsMax: {absMax}");
long minV = -absMax;
long maxV = absMax;
Vector3D? collisionPoint = null;
for (long vz = minV; vz < maxV && collisionPoint == null; vz++)
{
Console.WriteLine($"Brute forcing Z layer {vz}");
for (long vy = minV; vy < maxV && collisionPoint == null; vy++)
{
for (long vx = minV; vx < maxV && collisionPoint == null; vx++)
{
Vector3D newVelocity0 = new(
x: hails[0].Velocity.X - vx,
y: hails[0].Velocity.Y - vy,
z: hails[0].Velocity.Z - vz);
Hail shiftedHail0 = new(hails[0].Position, newVelocity0);
Vector3D newVelocity1 = new(
x: hails[1].Velocity.X - vx,
y: hails[1].Velocity.Y - vy,
z: hails[1].Velocity.Z - vz);
Hail shiftedHail1 = new(hails[1].Position, newVelocity1);
(bool intersects, double t, Vector3D? firstCollisionPoint) = shiftedHail0.Intersect3D(shiftedHail1, sameT: false);
if (intersects == false || firstCollisionPoint == null || t < 0.0) { continue; }
//Console.WriteLine($"Possible Rock: {firstCollisionPoint.Value.X}, {firstCollisionPoint.Value.Y}, {firstCollisionPoint.Value.Z} @ {vx}, {vy}, {vz} | {t}");
Hail[] shiftedHails = hails.Select(h =>
{
Vector3D newVelocity = new(
x: h.Velocity.X - vx,
y: h.Velocity.Y - vy,
z: h.Velocity.Z - vz);
Hail newHail = new(h.Position, newVelocity);
return newHail;
}).ToArray();
Vector3D currentCollisionPoint = firstCollisionPoint.Value;
bool allCollided = true;
for (int i = 2; i < shiftedHails.Length; i++)
{
(bool intersectsIter, double tIter, Vector3D? collisionPointIter) = shiftedHails[0].Intersect3D(shiftedHails[i], sameT: false);
if (
intersectsIter &&
tIter >= -0.001f &&
collisionPointIter != null &&
currentCollisionPoint.Cmp3D(collisionPointIter.Value) &&
true)
{
continue;
}
allCollided = false;
//Console.WriteLine($"... Invalid rock: {i}");
break;
}
if (allCollided)
{
collisionPoint = currentCollisionPoint;
}
}
}
}
return collisionPoint != null
? (collisionPoint.Value.X + collisionPoint.Value.Y + collisionPoint.Value.Z).ToString()
: string.Empty;
}
private string ResolvePart2_SolutionInDataSet(string[] inputs)
{
Hail[] hails = inputs.Select(input => new Hail(input)).ToArray();
// Check if any hail is doing the same as the rock
Hail? bestMatch = null;
for (int i = 0; i < hails.Length; i++)
{
bool allCollided = true;
for (int j = 0; j < hails.Length; j++)
{
if (i == j) { continue; }
(bool intersects, _, _) = hails[i].Intersect3D(hails[j]);
if (intersects) { continue; }
allCollided = false;
break;
}
if (allCollided)
{
bestMatch = hails[i];
}
}
if (bestMatch != null)
{
return (bestMatch.Value.Position.X + bestMatch.Value.Position.Y + bestMatch.Value.Position.Z).ToString();
}
return string.Empty;
}
public readonly struct Vector3D
{
public readonly long X;
public readonly long Y;
public readonly long Z;
public Vector3D(long x, long y, long z)
{
X = x;
Y = y;
Z = z;
}
public bool Cmp2D(Vector3D other)
{
return X == other.X && Y == other.Y;
}
public bool Cmp3D(Vector3D other)
{
return X == other.X && Y == other.Y && Z == other.Z;
}
} }
public readonly struct Hail public readonly struct Hail
{ {
public readonly Vector3D Position; public readonly Vector3D Position;
private readonly Vector3D _velocity; public readonly Vector3D Velocity;
public Hail(Vector3D position, Vector3D velocity)
{
Position = position;
Velocity = velocity;
}
public Hail(string input) public Hail(string input)
{ {
@@ -124,30 +387,49 @@ public class Day24 : IDay
y: Convert.ToInt64(strPosition[1]), y: Convert.ToInt64(strPosition[1]),
z: Convert.ToInt64(strPosition[2])); z: Convert.ToInt64(strPosition[2]));
string[] strVelocity = parts[1].Split(", "); string[] strVelocity = parts[1].Split(", ");
_velocity = new Vector3D( Velocity = new Vector3D(
x: Convert.ToInt64(strVelocity[0]), x: Convert.ToInt64(strVelocity[0]),
y: Convert.ToInt64(strVelocity[1]), y: Convert.ToInt64(strVelocity[1]),
z: Convert.ToInt64(strVelocity[2])); z: Convert.ToInt64(strVelocity[2]));
} }
public (bool intersects, double s, double t, Vector3D point) Intersect2D(Hail other) public (bool intersects, double s, double t) Intersect2D(Hail other)
{ {
long s_Div = (-other._velocity.X * _velocity.Y + _velocity.X * other._velocity.Y); long s_Div = (-other.Velocity.X * Velocity.Y + Velocity.X * other.Velocity.Y);
if (s_Div == 0) if (s_Div == 0)
{ {
return (false, 0, 0, new Vector3D()); return (false, 0, 0);
} }
double s = (-_velocity.Y * (Position.X - other.Position.X) + _velocity.X * (Position.Y - other.Position.Y)) / (double)s_Div; double s = (-Velocity.Y * (Position.X - other.Position.X) + Velocity.X * (Position.Y - other.Position.Y)) / (double)s_Div;
long t_Div = (-other._velocity.X * _velocity.Y + _velocity.X * other._velocity.Y); long t_Div = (-other.Velocity.X * Velocity.Y + Velocity.X * other.Velocity.Y);
if (t_Div == 0) if (t_Div == 0)
{ {
return (false, 0, 0, new Vector3D()); return (false, 0, 0);
} }
double t = (other._velocity.X * (Position.Y - other.Position.Y) - other._velocity.Y * (Position.X - other.Position.X)) / (double)t_Div; double t = (other.Velocity.X * (Position.Y - other.Position.Y) - other.Velocity.Y * (Position.X - other.Position.X)) / (double)t_Div;
Vector3D intersection = new((long)(Position.X + t * _velocity.X), (long)(Position.Y + t * _velocity.Y), 0); return (true, s, t);
return (true, s, t, intersection); }
public (bool intersects, double t, Vector3D? point) Intersect3D(Hail other, bool sameT = true)
{
(bool intersects, double s, double t) = Intersect2D(other);
if (intersects == false || (sameT && Math.Abs(s - t) > 0.001))
{
return (false, 0, null);
}
long zThis = (long)(Position.Z + t * Velocity.Z);
long zOther = (long)(other.Position.Z + s * other.Velocity.Z);
if (Math.Abs(zThis - zOther) > 0.001)
{
return (false, 0, null);
}
long yThis = (long)(Position.Y + t * Velocity.Y);
long xThis = (long)(Position.X + t * Velocity.X);
return (true, t, new Vector3D(xThis, yThis, zThis));
} }
} }
} }

View File

@@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>AdventOfCode2024.Tests</RootNamespace>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<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>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AdventOfCode2024\AdventOfCode2024.csproj"/>
</ItemGroup>
</Project>

View File

@@ -1,38 +0,0 @@
namespace AdventOfCode2024.Tests;
public class Day01_Tests
{
[Fact]
public void ResolvePart1__Example()
{
Day01 day = new();
string result = day.ResolvePart1([
"3 4",
"4 3",
"2 5",
"1 3",
"3 9",
"3 3",
]);
Assert.Equal("11", result);
}
[Fact]
public void ResolvePart2__Example()
{
Day01 day = new();
string result = day.ResolvePart2([
"3 4",
"4 3",
"2 5",
"1 3",
"3 9",
"3 3",
]);
Assert.Equal("31", result);
}
}

View File

@@ -1,38 +0,0 @@
namespace AdventOfCode2024.Tests;
public class Day02_Tests
{
[Fact]
public void ResolvePart1__Example()
{
Day02 day = new();
string result = day.ResolvePart1([
"7 6 4 2 1",
"1 2 7 8 9",
"9 7 6 2 1",
"1 3 2 4 5",
"8 6 4 4 1",
"1 3 6 7 9",
]);
Assert.Equal("2", result);
}
[Fact]
public void ResolvePart2__Example()
{
Day02 day = new();
string result = day.ResolvePart2([
"7 6 4 2 1",
"1 2 7 8 9",
"9 7 6 2 1",
"1 3 2 4 5",
"8 6 4 4 1",
"1 3 6 7 9",
]);
Assert.Equal("4", result);
}
}

Some files were not shown because too many files have changed in this diff Show More