-
Notifications
You must be signed in to change notification settings - Fork 0
Day 1
This one seems especially challenging.
While many people thought of replacing all occurrences of numbers with the actual number, it does not actually solve this question. For instance, a string 2eightwo
will get processed into 28wo
and produce an answer of 28. However, the actual answer is 22 because the last occurrence of a number is the "two" at the very end.
Our solution:
Use markers. Using the same example, 2eightwo
can be marked as:
[0] Number 2 @ position 0
[1] Number 8 @ position 1
[2] Number 2 @ position 5
Simple enough, the first digit is 2, and the last digit is also 2, so the answer is 22. This is an elegant solution to the problem for the following reasons:
- It can be implemented cleanly using procedural code.
- The full list of positions doesn't need to be stored, eliminating the need for a HashMap and increasing efficiency.
- It feels cool to talk about.
Our implementation
Since we can ignore all the values in the middle, we can just store the first and the current latest number as we check the line character by character. When checking each character, it would be intuitive to deal with a number character and to match the next several characters for a number string.
This implementation can be fully procedural with just some loops and conditions, and some u8 instead of a HashMap (array). You can see our example implementation in zig or go.