Today’s problem has us validating calibration data with unknown equations.
Part B gives a reason to break into Rust’s iterators.
As per use you can find the solutions discussed below on my github.
Part A
The Problem
We are given a list of calibrations; they consist of a target and elements.
A valid calibration is one whose target can be made by adding or multing the elements.
To verify our answer, we sum the targets of the valid calibrations.
The Solution
The solution is to iterate of all the combinations of adding and multing.
We can do this by generating all the combinations then testing them.
An easy way to generate all the combinations is to iterate from 0 to a number that has a binary 1 for each operator we need to apply: e.g.
In reading the part A, I thought it was very clear that more operators were on the way.
How did I design for this?
Mentally preparing to rewrite part A.
The bit tricks above are predicated on there being two operators, so /shrug.
Full Solution
Part B
The Twist
As expected, more ops.
The new operator is “concat”: i.e. 1 || 23 = 123
So, what’s a man to do.
How we Adapt
I mentioned above, the bitwise trick was predicated on there being two operators.
This is because we have binary numbers on computers at the time of writing.
So to add more operators, we increase the base!
But how?
Well I’m sure not writing abunch of bitwise math to go from binary to base 3.
So in comes Rust iterators.
What if we could get an iterator for all the numbers from 0 to 2222 in base 3?
Well we can, because software.
Additionally we can do so from the comfort of common idiom, because Rust.
What this will give us is access to ergonomic iteration of the data coming out of this class.
Each time a for loop calls next() the next base N will be calculated and returned in a form thats easy to parse.
See the usage in the full solution.
Will the iterator sorted out, all we need to do is properly reduce the values into their targets: