Add Day 06 solution, needs cleanup later
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using AdvenOfCode.Contracts;
|
||||
using Coordinate = (int x, int y);
|
||||
|
||||
namespace AoC_2025;
|
||||
|
||||
public class Day06 : IPuzzleSolver<long>
|
||||
{
|
||||
private (string[] operands, string[] numbers) ParsePuzzleInput(string path)
|
||||
{
|
||||
var puzzleInput = File.ReadAllLines(path)
|
||||
.Where(line => !string.IsNullOrWhiteSpace(line))
|
||||
.ToArray();
|
||||
var operands = puzzleInput[^1]
|
||||
.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
var numbers = puzzleInput[..^1];
|
||||
return (operands, numbers);
|
||||
}
|
||||
|
||||
public long SolvePart1(string pathToPuzzleInput)
|
||||
{
|
||||
var calculations = ParsePuzzleInput(pathToPuzzleInput);
|
||||
var numbers = calculations.numbers
|
||||
.Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
.Select(line => line.Index().ToArray())
|
||||
.SelectMany(tuples => tuples.Select(tuple => (tuple.Index, long.Parse(tuple.Item))).ToArray())
|
||||
.ToArray();
|
||||
var pivotedNumbers = numbers.GroupBy(tuple => tuple.Index);
|
||||
var indexedOperands = calculations.operands
|
||||
.Index()
|
||||
.Select(tuple => (tuple.Index, ParseOperand(tuple.Item)))
|
||||
.ToDictionary();
|
||||
var results = pivotedNumbers.Select(group =>
|
||||
group
|
||||
.Select(tuple => tuple.Item2)
|
||||
.Aggregate(indexedOperands[group.Key].opBaseValue,
|
||||
(acc, number) => indexedOperands[group.Key].operation(acc, number)));
|
||||
return results.Sum();
|
||||
}
|
||||
|
||||
public long SolvePart2(string pathToPuzzleInput)
|
||||
{
|
||||
var calculations = ParsePuzzleInput(pathToPuzzleInput);
|
||||
var operands = calculations.operands.Select(ParseOperand).Reverse().ToArray();
|
||||
List<List<long>> numberColumns = [];
|
||||
List<long> currentColumn = [];
|
||||
for (var i = 1; i <= calculations.numbers[0].Length; i++)
|
||||
{
|
||||
var current = calculations.numbers.Aggregate("", (current1, number) => current1 + number[^i]);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(current))
|
||||
{
|
||||
currentColumn.Add(long.Parse(current));
|
||||
}
|
||||
else
|
||||
{
|
||||
numberColumns.Add(currentColumn);
|
||||
currentColumn = [];
|
||||
}
|
||||
}
|
||||
numberColumns.Add(currentColumn);
|
||||
|
||||
return numberColumns
|
||||
.Select((column, colIndex) => column.Aggregate(operands[colIndex].opBaseValue, (acc, next) => operands[colIndex].operation(acc, next)))
|
||||
.Sum();
|
||||
}
|
||||
|
||||
private (Func<long, long, long> operation, long opBaseValue) ParseOperand(string operand) => operand switch
|
||||
{
|
||||
"+" => ((long a, long b) => a + b, 0),
|
||||
"*" => ((long a, long b) => a * b, 1),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(operand))
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user