98 lines
2.7 KiB
C#
98 lines
2.7 KiB
C#
// See https://aka.ms/new-console-template for more information
|
|
using System.Collections.Generic;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
var exParsed = new Day07Parsed("example-input.txt");
|
|
|
|
Console.WriteLine("Example Part01: {0}", exParsed.GetPart01());
|
|
Console.WriteLine("Example Part02: {0}", exParsed.GetPart02());
|
|
|
|
var pzParsed = new Day07Parsed("puzzle-input.txt");
|
|
|
|
Console.WriteLine("Puzzle Part01: {0}", pzParsed.GetPart01());
|
|
Console.WriteLine("Puzzle Part02: {0}", pzParsed.GetPart02());
|
|
|
|
class Day07Parsed : AdventCommon.ParsedInput
|
|
{
|
|
class Equation
|
|
{
|
|
public long LeftHandSide { get; set; }
|
|
public List<long> RightHandSide { get; set; } = new List<int>();
|
|
|
|
public int MaxOpCount
|
|
{
|
|
get
|
|
{
|
|
return RightHandSide.Count - 1;
|
|
}
|
|
}
|
|
|
|
List<long> ValidOps { get; set; } = new List<long>();
|
|
|
|
public bool IsValid()
|
|
{
|
|
for (int i = 0; i < (int)Math.Pow(2,MaxOpCount); i++)
|
|
{
|
|
long eqTotal = RightHandSide[0];
|
|
|
|
// a value of 0 for a given bit is +, 1 is *
|
|
for (int opIndex = 0; opIndex < MaxOpCount; opIndex++)
|
|
{
|
|
if ((i & (1 << opIndex)) == 0)
|
|
{
|
|
eqTotal += RightHandSide[opIndex + 1];
|
|
} else
|
|
{
|
|
eqTotal *= RightHandSide[opIndex + 1];
|
|
}
|
|
|
|
if (eqTotal > LeftHandSide)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (eqTotal == LeftHandSide)
|
|
{
|
|
ValidOps.Add(i);
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
public override int GetPart01()
|
|
{
|
|
int sum = 0;
|
|
foreach (var equation in Equations)
|
|
{
|
|
if (equation.IsValid())
|
|
{
|
|
sum += equation.LeftHandSide;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
List<Equation> Equations { get; set; } = new List<Equation>();
|
|
|
|
public Day07Parsed(string fileName) : base(fileName) { }
|
|
|
|
public override bool ParseLine(string line, object? context = null)
|
|
{
|
|
Equation equation = new Equation();
|
|
|
|
equation.LeftHandSide = Int32.Parse(line.Split(':')[0].Trim());
|
|
|
|
foreach (var v in line.Split(':')[1].Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
equation.RightHandSide.Add(Int32.Parse(v));
|
|
}
|
|
|
|
Equations.Add(equation);
|
|
|
|
return true;
|
|
}
|
|
} |