AOC 23 - Day 15 - Lens Library
Today was a easy day, just what I needed to catch up. The problem itself is about hashes, which is very easy with Python.
Part 1
Rules
For the part 1, we have to iter on the input sequence, and get the sum of each of their hashes. Each step of the sequence is separated by a coma.
The hash is calculated by these steps:
- Determine the ASCII code for the current character of the string.
- Increase the current value by the ASCII code you just determined.
- Set the current value to itself multiplied by 17.
- Set the current value to the remainder of dividing itself by 256
For example with
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
rn=1 becomes 30.
cm- becomes 253.
qp=3 becomes 97.
cm=2 becomes 47.
qp- becomes 14.
pc=4 becomes 180.
ot=9 becomes 9.
ab=5 becomes 197.
pc- becomes 48.
pc=6 becomes 214.
ot=7 becomes 231.
For a total of 1320.
Code
Let's start with the parsing:
return
Then the logic is easy and self-explanatory enough:
=
return
= 0
+=
*= 17
%= 256
return
And part 1 is done !
Part 2
Rules
Part 2 is a bit longer to explain, but not that complicated.
We now have a box of 256 empty boxes. Each instruction can be one of 2 types.
If the instruction has =
in it, we will update or create a box. For this, we will do the following:
- split the string in 2.
rn=1
would becomern
(the label) and1
(the focal length) - get the hash of the label. For
rn
it is0
. - look in the box having an id matching the computed hash.
- if this box do not contains a lens with this label, create a lens with the label and the focal length.
- if this box contains a lens with this label, just update the focal length.
If the instruction ends with -
, the steps are:
- remove the trailing
-
to get the label - get the hash of the label.
- look in the box having an id matching the computed hash.
- if the box contains a lens with the same label, delete this box
- otherwise do nothing
We then have to return the sum of the focusing power. The focusing power of each step is the multiplication of the following values:
- One plus the box number of the lens in question.
- The slot number of the lens within the box: 1 for the first lens, 2 for the second lens, and so on.
- The focal length of the lens.
Code
Nothing difficult here. I chose to use a dataclass to represent the len:
:
:
We then have to write the functions for the 2 instructions.
=
=
=
=
return
And then plug them into the main function, calculating the focusing power at the end
=
: =
=
,
= 0
+= * *
return
And that's it for day 15.
All the code is available on github