
Day 3, part 2
Day 3 challenge of the mighty Advent of Code 2024
Introduction
This article is a continuation of Day 3, part 1. We will be using what we have done in part 1, so before you jump into this article, please get familiar with the previous one. This part of the challenge is available only when you successfully finished the part 1. The second part of the challenge is described under -- Part Two -- section here.
What is the new problem
Now we are asked to search all * that are adjacent to exactly two numbers and then multiply those numbers for each * and to get gear ratio add them together to get the final result. Lets take a look at the test data again.
1467..114..
2...*......
3..35..633.
4......#...
5617*......
6.....+.58.
7..592.....
8......755.
9...$.*....
10.664.598..In this grid there are two * that are adjacent to exactly two numbers. Those numbers are 467 and 35 for the first * and the gear ratio is 16345. The second pair of numbers are 755 and 598 and the gear ratio is 451490, so the result we are looking for here is 467835.
Solution
As you remember from the part 1, when we were looking for numbers, I was considering two options:
- looking for symbols and then for numbers adjacent to it
- looking for numbers and then for adjacent symbols
For the reasons described there, I decided that its easier to follow the second solution. This time I think I can do it like so: - For the numbers we have found, lets check their neighborhoods and gather all the asterisks with the reference to the number they were found next to.
- Group the found asterisks based on their position, so we have the count of how many times they have appeared and which numbers were next to it.
- Filter only these asterisks which were counted twice.
- Calculate the gear ratio for each pair of numbers.
- Sum the numbers to get final result.
Finding the asterisks adjacent to numbers
We can take a look at how did we find the numbers adjacent to symbols before using the filterPartNumbers and especially the isSymbolInArea functions.
Now instead of filtering, we have to gather each asterisk data in an array.
1function findAsterisksAdjacentToNumbers(numbersWithAreas, grid) {
2 const foundAsterisks = [];
3 numbersWithAreas.forEach((numberWithArea) => {
4 const { x0, x1, y0, y1 } = numberWithArea.area;
5 for (let x = x0; x <= x1; x++) {
6 for (let y = y0; y <= y1; y++) {
7 if (grid[y][x] === '*') {
8 foundAsterisks.push({ x, y, number: numberWithArea });
9 }
10 }
11 }
12 });
13 return foundAsterisks;
14}
15const asterisksAdjacentToNumbers = findAsterisksAdjacentToNumbers(numbersWithAreas, inputGrid);
16console.log('Asterisks adjacent to numbers: ', asterisksAdjacentToNumbers);After running this script, we can see this output in the terminal:
1Asterisks adjacent to numbers: [
2 {
3 x: 3,
4 y: 1,
5 number: { number: 467, startInx: 0, endInx: 2, lineIdx: 0, area: [Object] }
6 },
7 {
8 x: 3,
9 y: 1,
10 number: { number: 35, startInx: 2, endInx: 3, lineIdx: 2, area: [Object] }
11 },
12 {
13 x: 3,
14 y: 4,
15 number: { number: 617, startInx: 0, endInx: 2, lineIdx: 4, area: [Object] }
16 },
17 {
18 x: 5,
19 y: 8,
20 number: { number: 755, startInx: 6, endInx: 8, lineIdx: 7, area: [Object] }
21 },
22 {
23 x: 5,
24 y: 8,
25 number: { number: 598, startInx: 5, endInx: 7, lineIdx: 9, area: [Object] }
26 }
27]As we can see we found 5 asterisks where two of those are duplicated. This means we have total of 3 asterisks, two of which are adjacent to exactly two numbers. We also have a reference to the numbers, so it will be easier to use these numbers later.
Time to save our progress.
1git add .
2git commit -m "find asterisks adjacent to numbers"Grouping asterisks
Now we can tweak the data a little and create groups for each individual asterisk with the array of its numbers.
1function groupAsterisks(asterisksWithNumbers) {
2 return asterisksWithNumbers.reduce((group, asteriskWithNumber) => {
3 const { x, y, number } = asteriskWithNumber;
4 const id = `x${x}y${y}`;
5 if (!group[id]) {
6 group[id] = [number];
7 } else {
8 const currentGroup = group[id];
9 group[id] = [...currentGroup, number];
10 }
11 return group;
12 }, {});
13}
14const asteriskGroups = groupAsterisks(asterisksAdjacentToNumbers);
15console.log('Asterisk groups: ', asteriskGroups);In this simple function, we use reduce method to build an object with key as a combination of x and y position in the grid, which is unique to each asterisk. Then we gather numbers for each asterisk in an array. If the object does not exist we create a new one, and if it does we append the new number to the array. The result is:
1Asterisk groups: {
2 x3y1: [
3 { number: 467, startInx: 0, endInx: 2, lineIdx: 0, area: [Object] },
4 { number: 35, startInx: 2, endInx: 3, lineIdx: 2, area: [Object] }
5 ],
6 x3y4: [
7 { number: 617, startInx: 0, endInx: 2, lineIdx: 4, area: [Object] }
8 ],
9 x5y8: [
10 { number: 755, startInx: 6, endInx: 8, lineIdx: 7, area: [Object] },
11 { number: 598, startInx: 5, endInx: 7, lineIdx: 9, area: [Object] }
12 ]
13}We can commit the changes.
1git add .
2git commit -m "group asterisk numbers"Get gear ratio number pairs
Now we can simply filter the asterisks with two numbers in the array and return only the array of those pairs. The id is not needed anymore.
1function getGearRatioGroups(groups) {
2 return Object.values(groups).filter((group) => group.length === 2);
3}
4const gearRatioNumberPairs = getGearRatioGroups(asteriskGroups);
5console.log('Gear ratio pairs: ', gearRatioNumberPairs);1Gear ratio pairs: [
2 [
3 { number: 467, startInx: 0, endInx: 2, lineIdx: 0, area: [Object] },
4 { number: 35, startInx: 2, endInx: 3, lineIdx: 2, area: [Object] }
5 ],
6 [
7 { number: 755, startInx: 6, endInx: 8, lineIdx: 7, area: [Object] },
8 { number: 598, startInx: 5, endInx: 7, lineIdx: 9, area: [Object] }
9 ]
10]Looks good to me! Great! We can commit the changes.
1git add .
2git commit -m "find number pairs for gear ratio"Calculating the gear ratio
To get the gear ratio for each pair of numbers, we can simply map through each pair and return the product of multiplication for each.
1function getGearRatio(gearRatioNumberPairs) {
2 return gearRatioNumberPairs.map((group) => group[0].number * group[1].number);
3}
4const gearRatios = getGearRatio(gearRatioNumberPairs);
5console.log('Gear ratios: ', gearRatios);1Gear ratios: [ 16345, 451490 ]This is exactly what we were looking for.
Lets save the changes once more.
1git add .
2git commit -m "calculate gear ratios"Summing up the gear ratios
There is not much to say here. We did this already many times so lets do it once more.
1function getGearRatioResult(gearRatios) {
2 return gearRatios.reduce((acc, curr) => (acc += curr), 0);
3}
4const sumOfGearRatios = getGearRatioResult(gearRatios);
5console.log('Sum of gear ratios: ', sumOfGearRatios);1Sum of gear ratios: 467835And we get the correct result as expected. Lets commit the changes.
1git add .
2git commit -m "sum up gear ratios"Final result
Lets run what we have using the real input data.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');The following result is showed in the terminal.
1Sum of gear ratios: 81709807We can now paste it in the answer input field and click [Submit]. Drum roll please!
And...
Aha! We did it!
The final step is to commit our final code.
1git add .
2git commit -m "day 3 part 2 final result"We can be proud of ourselves as we successfully completed the day 3 puzzle. Allow me to invite you to Day 4, part 1 and see you there!