Deciphering Engine Schematics
Day 3 of Advent of Code presented us with a mechanical mystery: an engine part was missing, and it was our task to identify it by summing up part numbers in the engine schematic. The catch? Only numbers adjacent to specific symbols counted.
Our Solution
For Part One, we crafted a TypeScript function to meticulously parse through the engine schematic and calculate the sum of valid part numbers.
Part One
: Summing Part Numbers
const getSurroundingString = (
line: string,
topLine: string,
bottomLine: string,
matchIndex: number,
digitLength: number
): string => {
const leftIndex = matchIndex > 0 ? matchIndex - 1 : 0;
const rightIndex = matchIndex + digitLength;
return [
topLine.slice(leftIndex, rightIndex + 1),
bottomLine.slice(leftIndex, rightIndex + 1),
line[leftIndex] ?? "",
line[rightIndex] ?? "",
].join("");
};
export default function partOne(schematic: string[]): number {
const digitRegex = /\d+/g;
const hasSymbolRegex = /[^.\d]+/g;
return schematic.reduce((acc, line, index) => {
const topLine = index > 0 ? schematic[index - 1] : "";
const bottomLine = schematic[index + 1] ?? "";
return (
acc +
[...line.matchAll(digitRegex)]
.map(match => ({ digit: match[0], matchIndex: match.index! }))
.filter(({ digit, matchIndex }) => {
const surroundingString = getSurroundingString(
line,
topLine,
bottomLine,
matchIndex,
digit.length
);
hasSymbolRegex.lastIndex = 0;
return hasSymbolRegex.test(surroundingString);
})
.reduce((innerAcc, { digit }) => innerAcc + Number(digit), 0)
);
}, 0);
}
Our approach involved identifying numbers in the schematic and checking their surrounding characters for specific symbols. If a number was adjacent to a symbol, it was included in our sum.
The Challenge of Part Two
While we successfully solved Part One, Part Two presented a level of complexity that proved too difficult within my personal time constraints. This highlights an important aspect of coding challenges: sometimes, it’s about balancing what can be achieved with the resources and time available.
Conclusion
Day 3’s puzzle reinforced the importance of iterative problem-solving and continuous code improvement. It was a valuable exercise in parsing complex data structures.
Stay tuned as we continue to tackle more Advent of Code challenges!