add level 3 and backport textparser changes

This commit is contained in:
2024-12-04 12:47:10 +01:00
parent 377ef9afe8
commit 5b9ad5766b
10 changed files with 208 additions and 9 deletions

14
Level3/Level3.csproj Normal file
View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Common/Common.csproj" />
</ItemGroup>
</Project>

80
Level3/Level3Solver.cs Normal file
View File

@@ -0,0 +1,80 @@
namespace AoC24;
using AoC24.Common;
using AoCLevelInputProvider;
using Parsing;
using Parsing.Schema;
using Parsing.Tokenization;
public class Level3Solver : FragmentLevelSolverBase
{
public override int LevelNumber
{
get { return 3; }
}
protected override FragmentSchemaBuilder DefineInputSchema(FragmentSchemaBuilder schemaBuilder)
{
return schemaBuilder
.StartOptions()
.Option()
.Expect("mul(")
.Expect(InputType.Integer, "num1")
.Expect(",")
.Expect(InputType.Integer, "num2")
.Expect(")")
.Option()
.Expect("do()", "on")
.Option()
.Expect("don't()", "off")
.EndOptions();
}
public override string SolveFirstStar()
{
return this.GetData()
.AsFragments()
.ConvertAll((Fragment f) =>
{
if(!f.ContainsKey("num1") || f["num1"].Count == 0)
{
return 0;
}
int numProd = int.Parse(f["num1"][0]);
numProd *= int.Parse(f["num2"][0]);
return numProd;
})
.ReduceData((int num1, int num2) => num1 + num2)
.ToString();
}
public override string SolveSecondStar()
{
bool isOn = true;
return this.GetData()
.AsFragments()
.ConvertAll((Fragment f) =>
{
if(f["on"].Count > 0)
{
isOn = true;
return 0;
}
if(f["off"].Count > 0)
{
isOn = false;
return 0;
}
if(!isOn)
{
return 0;
}
int numProd = int.Parse(f["num1"][0]);
numProd *= int.Parse(f["num2"][0]) ;
return numProd;
})
.ReduceData((int num1, int num2) => num1 + num2)
.ToString();
}
}

24
Level3/Program.cs Normal file
View File

@@ -0,0 +1,24 @@
// See https://aka.ms/new-console-template for more information
using AoC24;
var levelSolver = new Level3Solver();
var solution1 = levelSolver.SolveFirstStar();
var solution2 = levelSolver.SolveSecondStar();
if (!string.IsNullOrEmpty(solution1))
{
Console.WriteLine("Solution for example 1 is: " + solution1);
}
else
{
Console.WriteLine("Example 1 has not been solved yet!");
}
if (!string.IsNullOrEmpty(solution2))
{
Console.WriteLine("Solution for example 2 is: " + solution2);
}
else
{
Console.WriteLine("Example 2 has not been solved yet!");
}