Day 3: Mull It Over
Part 1
Today's task consists of running corrupt multiplication instructions to find out the final total result.
The instructions are only valid when in the format of:
mul(123,4)
This led me to immediately use regex.
To begin I made a parser that would extract all the valid instructions.
function parse(input: string) {
const regexMatches = input.match(/mul\(\d+,\d+\)/mg);
return regexMatches?.map(string => string.match(/\d+/mg)?.map(Number));
}
The above parser will take in the whole input string then using regex find the valid multiplication instructions. I next use a map on the matches to further extract the digits within the instruction before returning them as an array of numbers.
[
[ 338, 323 ], [ 746, 703 ], ...
]
I next created a simple instruction to process the multiplication.
function executeInstruction(input: number[]) {
return input[0] * input[1];
}
Before finally using a reducer to sum the total executed instructions as per the task's requirements.
const total = parse(input).reduce(
(sum, instructionData) => sum + executeInstruction(instructionData), 0,
);
Part 2
Part 2 introduces conditional statements, these are do()
and don't()
.
It's also worth noting that only the most recent conditional statement applies to the instruction, with all instructions enabled by default.
To begin I update my regex to now match the new do and don't conditions present.
I will then for each regex match, check if it is a do or don't and toggle the enabled boolean as a result.
Then when the match is a mul
, and enabled is true I perform the same normal behaviour of digit extraction.
Finally, the parsed input is returned to the same code as part 1 for a final total to be calculated.
function parse(input: string) {
// enabled by default
let enabled = true;
const results: number[][] = [];
const regexMatches = input.match(/do\(\)|don't\(\)|mul\(\d+,\d+\)/mg);
regexMatches.forEach((regexMatch) => {
if (regexMatch === 'do()') {
enabled = true;
}
else if (regexMatch === 'don\'t()') {
enabled = false;
}
else if (regexMatch.slice(0, 3) === 'mul') {
if (enabled) {
// console.log(regexMatch.match(/\d+/mg)?.map(Number));
results.push(regexMatch.match(/\d+/mg)?.map(Number));
}
}
});
return results;
}
Below is same as part 1.
function executeInstruction(input: number[]) {
return input[0] * input[1];
}
const total = parse(input).reduce(
(sum, instructionData) => sum + executeInstruction(instructionData), 0,
);
This successfully generates the part 2 answer.