Day 6Trash Compactor

View puzzle description on Advent of Code

Part one here was pretty straightforward, but part two took some thinking.

I went through a few different approaches — changing my approach significantly when I spotted that numbers can be left or right aligned — before realising that I could just process all lines together from right-to-left, then top to bottom for each column. When we get to an operator we the know we've processed all the numbers in that block and we can then perform the calculation and add the result to the total.

I'm a bit ill as I do this and my solution nearly reflected that as I came quite close to using an eval, but in the end clearer heads prevailed and I'm quite happy with my operator object and reduce combo.

const add = (a: number, b: number) => a + b;
const multiply = (a: number, b: number) => a * b;
const operationsMap = new Map([
['+', add],
['*', multiply],
]);
export default (input: string): number => {
const arr2d = input.split('\n').map(line => line.trim().split(/\s+/));
let total = 0;
for (let x = 0; x < arr2d[0].length; x++) {
const operationSymbol = arr2d.at(-1)![x];
const operation = operationsMap.get(operationSymbol)!;
let runningTotal = 0;
for (let y = 0; y < arr2d.length - 1; y++) {
const value = Number(arr2d[y][x]);
if (runningTotal === 0 && operation === multiply) {
runningTotal = operation(1, value);
} else {
runningTotal = operation(runningTotal, value);
}
}
total += runningTotal;
}
return total;
};