Summary
See Part 1
- There are 256 boxes (0-255)
- String format:
{label}{operation}{lens_focal_length}
- Hash the label to get the correct box number
- If operation is
=
place a lens with that focal length into box with the label- If label is already in box, replace with new focal length
- If operation is
-
take the lens with that label from the box - More than 1 Lenses can be in a box, order matters
- Calculate the total focal strength through all boxes
To calculate the focal strength of a Lens you
Lens
While I could place the raw strings in boxes and decode them when needed, I decided to make a lens class to makes it a little easier on myself. The operation isn’t associated with the final lens, so that attribute isn’t included.
|
|
Note: the Symbol.toStringTag
method isn’t important, it’s used to output
the class in a usable format other than [Object object]
Boxes
Boxes will be a 2D array filled with Lens objects, Lens[][]
, I wrote a
function to predefine them:
Hashing
Hashing the label requires repackaging the functionality created in Part 1. This actually was confusing me because I was hashing the whole string like in Part 1, but it actually requires the label
Parsing
Using the strings provided in the examples, I started with function that grabbed chars at specific indices
This idea worked great in the example, but after not getting the correct results using the input and doing a little debugging the labels aren’t a set 2 characters. Instead I used a regular expression and instead of writing 3 separate functions I wrote one that would return them all at once.
|
|
I think for readability it might have been better to define an interface
for the return instead of using a any[]
type. This wouldn’t have been
the look I was going for, I was aiming more towards how Python can
return variables in tuples. The trade-off is these 3 variables should be
constants instead of mutable.
Sorting
This is the meat of the challenge: do the encoded operations and sort lenses into boxes. Generally self explanatory: push new lenses into the correct array and slice the array to get a lens out.
I did write a helper function that returns the lens object if it’s in the box
already. Originally this function return a false
and was typed boolean
, but
the transcoder yelled at me because true
doesn’t have a attribute
focal_length
; I guess that’s the trade-off of using TypeScript, but returning
undefined is a little more fitting in this situation.
|
|
Focal Strength
To get the final answer it takes a nested loop and keeping track of the indices:
..and Fin.
Edit: markdownlint, textlint and meta TOML -> YAML