Module advent_of_code_2021::day_3 [−][src]
Expand description
This is my solution for Advent of Code - Day 3 - Binary Diagnostic
Today the task was to analyse a sequence of binary data with a bunch of bitwise operators. I ended up reworking both parts after I originally got them working with more convoluted code.
parse_input is used to covert the binary strings into numbers, and also returns the number
of bits per string as that is needed for some of the bitwise tricks later.
analyse_diagnostics solves part one, deferring some logic to count_bit. Originally this
was a double for loop over data and bit position, storing the counts into a mutable Veccount_bit for my original solution to part two, and once written I refactored
analyse_diagnostics to use it as well. When I later refactored analyse_life_support to
no longer need count_bit, analyse_diagnostics was still cleaner when using
count_bit so I left it as is.
analyse_life_support solves part two. Originally it used count_bit to determine if
the bits at the current position were majority set or not, then filtered the current subset
based on that. The current partition based approach is easier to understand what is going on.
Functions
This solves part one, returning the pair of required values. It calculates the gamma value by
iterating through each bit in the input strings and comparing the result of count_bit to the
size of the data. The epsilon value is the bitwise inverse of that.
This solves part two, returning the pair of required values. The solution calls for successively filtering the input array until only one value array, which works well as a recursive function. The base case for this is when the provided array is of length 1, and returns the remaining value if it is present. Otherwise split the input based on whether the bit we care about is set, then recurse the largest/smallest half based on which value is being calculated, and the bit position advanced by 1. Unlike part one, the recursion means there isn’t a neat trick to invert the first result to product the second, so the recursive function is called twice, with a flag used to switch the mode.
Return the number of values in the data where all the bits set in the bitmask are also set in
the value. Utility function used by analyse_diagnostics. For this puzzle, only one bit is
set in the mask at a time.
Returns a pair of the parsed data and the length of the bit strings. Delegates to the built in
[usifix ze::from_str_radix]. The length is needed for some of the bitwise tricks.
The entry point for running the solutions with the ‘real’ puzzle input.
