87 lines
3.3 KiB
C#
87 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection.Emit;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Text.RegularExpressions;
|
|
using System.IO.Compression;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace Advent24
|
|
{
|
|
internal class Day7
|
|
{
|
|
public Day7()
|
|
{
|
|
String fileData = System.IO.File.ReadAllText(@"..\..\..\inputd7.txt");
|
|
|
|
String[] equations = fileData.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
Int64 totalCalibrationResult = 0;
|
|
|
|
Boolean concatenationEnabled = true;
|
|
|
|
Int64 @base = concatenationEnabled ? 3 : 2;
|
|
|
|
foreach (String equation in equations)
|
|
{
|
|
String[] subequation = equation.Split(':', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
Int64 testValue = System.Convert.ToInt64(subequation[0]);
|
|
|
|
String[] operands = subequation[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
Int64[] intermediateResults = new Int64[(Int64)Math.Pow(@base, operands.Length-1)];
|
|
|
|
Int64 intermediateResultIndex = (Int64)Math.Pow(@base, operands.Length - 1);
|
|
|
|
Int64 numberOfSections = @base;
|
|
|
|
Int64 sectionWidth = intermediateResults.Length / numberOfSections;
|
|
|
|
Int64 operandIndex = 0;
|
|
|
|
// copy first operand to all locations - half the total number of location will be to add the second operand, the other half will be to multiply it
|
|
for(Int64 i = 0; i < intermediateResultIndex; i++)
|
|
intermediateResults[i] = System.Convert.ToInt64(operands[operandIndex]);
|
|
|
|
operandIndex++;
|
|
|
|
while (operandIndex < operands.Length)
|
|
{
|
|
sectionWidth = intermediateResults.Length / numberOfSections;
|
|
|
|
for (Int64 sectionNumber = 0; sectionNumber < numberOfSections; sectionNumber++)
|
|
|
|
|
|
for (Int64 i = sectionNumber * sectionWidth; i < (sectionNumber + 1) * sectionWidth; i++)
|
|
if (sectionNumber % @base == 0)
|
|
// first choice of operator = +
|
|
intermediateResults[i] += System.Convert.ToInt64(operands[operandIndex]);
|
|
else if (sectionNumber % @base == 1)
|
|
// second choice of operator = *
|
|
intermediateResults[i] *= System.Convert.ToInt64(operands[operandIndex]);
|
|
else
|
|
// third choice of operator = || (concatenation)
|
|
intermediateResults[i] = intermediateResults[i] * (Int64)Math.Pow(10, operands[operandIndex].Length) + System.Convert.ToInt64(operands[operandIndex]);
|
|
|
|
numberOfSections *= @base;
|
|
operandIndex++;
|
|
}
|
|
|
|
if (intermediateResults.Contains(testValue))
|
|
{
|
|
// testValue is possible
|
|
totalCalibrationResult += testValue;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine("totalCalibrationResult = {0:d}", totalCalibrationResult);
|
|
|
|
// to keep the console window from closing
|
|
Console.ReadKey();
|
|
}
|
|
}
|
|
}
|