AOC 23 - Day 03 - Gear Ratios
For the third day, we require a gondola lift. Of course, it's broken. We need to help finding the missing mechanic part.
Part 1
Rules
For the first part, we need to find which number is a part or not. A number is a part if it's adjacent, even diagonally, to any symbol which is not .
.
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361.
Code
To solve this, a simple flood-fill like algorithm is enough; we iterate from left to right, and up to bottom, and for each found digit, we go from left to right to gather the full number, and check if any of the digits is adjacent to a symbol. If the digit has a digit on its left, we ignore it, since it means its part of a number we already processed.
=
=
=
continue # this part number already has been evaluated
return
return True
+= 1
return False
=
+=
+= 1
return
Part 2
Rules
For the part 2, we need to find all the values *
with exactly two part number adjacent to it, multiply these two number, and return the sum of this.
Code
I started trying to find a solution to keep track of all the part number processed by (y, x), but I then realize that a number touching the tile *
is by definition a product number.
With this new solution, I just have to:
- update the
get_part_number
function, so it can retrieve a number from any side, and delete the number so we count each number once - for each tile
*
, retrieve all the adjacent numbers Then, if the tile has exactly 2 numbers, we add the product to the total. This give us:
"""Returns the complete number from this tile as an `int`, or `None`.
A complete number is the concatenation of the digits linked to the initial tile on the x-axis.
If the tile is not a digit, this function will return `None`
If `delete` is set to `True`, each digit from the number will be replaced by `.` once read.
"""
=
return None
-= 1
+= 1
+=
=
+= 1
return None
return
=
= 0
=
+= *
return
=
=
return
And the day is solved !
All the code is available on github