Hello! Let’s take a look at solving the problem for day 04.
Spoilers Ahead! The full solution to the problem is available here.
Problem
Given a batch of inputs separated by empty lines, indicating passports with a predefined number of fields, validate the fields in the passport, and return the total number of such valid passports.
Sample Input:
wherein the fields are:
NOTE: Based on the problem, A valid passport has all fields mentioned above, and cid alone is optional.
Alright! The problem is pretty straightforward. We have to essentially just perform string parsing, identify if all the required fields are present in a password. An important step distinct to this problem is that each field in the passport input can extend to more than 1 line, and each batch is separated by an empty line.
Unlike previous problems, we need to do some additional things to get our input to validate.
Let’s look at how we can process the input.
Nice! Now onto the actual validation step. The main algorithm for the validation would be :
Split a given passport string by space and save as an array.
Create a hashmap of the required fields. The hashmap would also need to track both the count and the value of the field for later use.
Iterate through all the fields in the passport, and update the hashmap’s count (increment by 1) and set the value. The hashmap has key as the field, and the value is a (count, field_value).
Now make sure that all fields in the hashmap have a count > 0.
NOTE: The should_validate_fields and the validate_fields function are not necessary for part 01 of the problem and will be useful only for part 02.
Part 02
The only additional constraint for Part 02 is that every field has some rules that it needs to follow in order for the passport to be marked as valid. So Part 02 is just more validation on top of Part 01. Let’s code that up!
As we saw earlier our validate_passport function would remain the same, and the stricter validation is enforced by the should_validate_fields boolean passed as a parameter.
The process function would also need to pass in this value, so that would look something like: