advent_of_code_2024/Level3/Level3Solver.cs

81 lines
2.7 KiB
C#

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();
}
}