Odometer
August 3, 2018
Today’s exercise is an Amazon interview question:
An odometer variously uses letters and digits in its reading; for instance, an odometer might have a reading of G7TS39. Incrementing the odometer means adding 1 to a digit or increasing to the next letter to the next letter, with a carry to the next column when appropriate. Thus, G7TS39 increments to G7TS40 and G7TZ99 increments to G7UA00. As a special case, the odometer never increases in size, but rolls over, so the next odometer reading after Z9ZZ99 is A0AA00. An odometer position that initially contains a digit always contains a digit, and an odometer position that initially contains a letter always contains a letter, so 1Z9 increments to 2A0.
Your task is to write a program to increment an odometer. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python.
Here’s a solution in C.
Example:
Python
Because everything is better with a regular expression. ;-)
It works by replacing anything that is followed by nothing but ‘9’s and ‘Z’s. Replace it with a ‘0’ if it was a ‘9’, by an ‘A’ if it was a ‘Z’, or by the next character in sequence otherwise.
@ProgrammingPraxis: Submitted version for Mumps. Haven’t seen it.
Mumps version
Perl6 solution delegating some work to the built-in succ method: https://docs.perl6.org/routine/succ
Here’s a solution in Python that uses numpy functions ravel_multi_index and unravel_index.
The odometer reading is treated as the subscript for indexing into a higher order array. The subscript index is converted to the index for a corresponding flattened version of the array. This index is incremented, and then converted back to a subscript.
Output:
August 3rd, 2018.c:
The solution is known to run on an Apple Power Mac G4 (AGP Graphics) (450MHz processor, 1GB memory) on both Mac OS 9.2.2 (International English) (the solution interpreted using Leonardo IDE 3.4.1) and Mac OS X 10.4.11 (the solution compiled using the command line:
gcc -c August\ 3rd,\ 2018.c; gcc August\ 3rd,\ 2018.o -o August\ 3rd,\ 2018
).(I’m just trying to solve the problems posed by this ‘site whilst I try to get a job (and I’ve solved this problem in particular to test my understanding of compiling using the command line – an understanding that might be necessary if I’m to release an executable of my SDL2 joystick interrogator utility, or of my entry for Ludum Dare 5, for the Raspberry Pi); I’m well-aware that my solutions are far from the best – but, in my defence, I don’t have any traditional qualifications in computer science :/ )