ps. look out for all my other solutions for Advent of Code challenges here.
See details of the challenge here.
Let’s start by adding a hash function that’ll take an input string and return the hexdecimal representation of its MD5 hash.
From there, we can create an infinite sequence of hash values generated by concatinating the input and an increasing index (as per the instruction). But, remember, we’re only interested in hash values that starts with 5 zeroes.
Once we have this sequence of interesting hash values, part 1 requires us to take the first 8 and make a password out of it.
As the door slides open, you are presented with a second door that uses a
slightly more inspired security mechanism. Clearly unimpressed by the last
version (in what movie is the password decrypted in order?!), the Easter Bunny
engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also
indicates the position within the password to fill. You still look for hashes
that begin with five zeroes; however, now, the sixth character represents the
position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password.
Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015…; so, 5
goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is
ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e…; so,
e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place,
producing the password 05ace8e3.
Given the actual Door ID and this new method, what is the password? Be extra
proud of your solution if it uses a cinematic “decrypting” animation.
We can reuse the inifinite sequence of interesting hash values we constructed earlier, but this time around we need to also filter out hash values whose 6th character is not 0-7.
Additionally, we need to track the first hash value for each position.
The first idea I had was to use a mutable Option<char> (length 8) to represent the password, and then iterate over the valid hash values until that array is filled with Some x. But this approach felt too imperative for my liking..
I couldn’t use a fold as it will fold over all the inputs.. however, I can use a scan which yields the intermediate results as a sequence – which I can then skip until I have 8 hash values.
I can also use an immutable Set to represent all the positions that are still unoccupied as I iterate through the hash values.
Whilst part 1 was not computationally light, it did complete in a matter of seconds on my laptop. Part 2 took more than a minute to finish so if anyone knows a good way to speed things up please leave a comment to this post.