Day 2: Gift Shop
Finding invalid product IDs:: ON THIS PAGE 3
Part 01
Day 1 done, we made it to the gift shop! (who is even visiting this shop??).
An elf has added a bunch of invalid product IDs to their database, and we are given a list of ranges we need to check.
11-22,95-115,998-1012,1188511880-1188511890,222220-222224,...
An invalid product ID is made only of some sequence of digits repeated twice. So, 55 (5 twice), 6464 (64 twice), and 123123 (123 twice).
First step is to parse the input into a more manageable state. Rust allows us to write a small compact "one-liner", which is in a functional style. Chaining-methods
// create a struct to hold our range
// parsing the input
let ranges: = input
.split
.map // Range must implement FromStr
.?;
Since we are parsing a string to our Range struct we need to FromStr.
With that out of the way we now need to loop through all our nicely parsed data.
for range in ranges
We didn't need to implement a custom iter on our object we could have...
for num in range.start..=range.end
But since I am doing this to learn some Rust I figured why not...
Pattern
One observation we can make is that the invalid product IDs will have have some sequence of its numbers repeated twice. Meaning only numbers that have an even amount of digits in them can be considered!
Since we know the subsequence is repeated twice that means that if we split the number in half, the first half must equal the second half
Part 02
For part 02 the added twist is a product ID is invalid if it is made only of some sequence of digits repeated at least twice.
Ex. 123123123 length = 9
| Iteration | Pattern Length | Divisible? (9 % len) | Candidate | Check | Result |
|---|---|---|---|---|---|
| i = 0 | 1 | Yes | 1 | 111111111 | ❌ Fail |
| i = 1 | 2 | No | - | - | Skip |
| i = 2 | 3 | Yes | 123 | 123123123 | ✅ Match |