Sprite row decoder
EasyOnline Assessment
Decode one row of a pixel-art sprite stored in a compact run-length format, and reject rows that are corrupt.
A row is written as a sequence of runs. A run is a count followed by a single uppercase color letter, for example 3R means three red pixels. Runs are read left to right and every run ends at its color letter. Any characters left over after the last letter form one more (unfinished) run.
A run is well formed only if its count is written with one or two digits, has no leading zero, and is between 1 and 99, and the run ends with a color letter. (0R, 05R, 100R, R, and a trailing 7 with no letter are all malformed.)
Check the runs in order. The first run k (counting from 1) that breaks any of these rules makes the answer "BAD RUN k", where the checks for one run are made in this order:
- The run is well formed.
- Its color differs from the previous run's color (a writer must merge equal neighbours, so
2R3Ris corrupt). - Adding its count keeps the running pixel total at or below
width.
If every run passes but the total is less than width, the answer is "SHORT BY d", where d is the number of missing pixels. An empty row therefore gives "SHORT BY <width>".
Otherwise the row is valid and the answer is the decoded string of exactly width letters.
Input: row, a string, and width, the number of pixels the row must contain.
Output: the decoded string, or one of the error strings above.
Example 1
- Input:
- ["3R2G1B",6]
- Output:
- "RRRGGB"
- Explanation
- The runs are
3R,2G,1B: three R, two G, one B. They are all well formed, never repeat a color back to back, and add up to the width of 6, so the decoded row isRRRGGB.
Example 2
- Input:
- ["12R04G3B",10]
- Output:
- "BAD RUN 1"
- Explanation
- The row splits into
12R,04G,3B. The second run has a leading zero in its count, so it is malformed and the answer names run 2. (The total of 12 + 4 + 3 would also have overshot the width of 10, but the malformed run is found first.)
Example 3
- Input:
- ["4R3G",9]
- Output:
- "SHORT BY 2"
- Explanation
4Rand3Gare fine and fill 7 of the 9 pixels. Nothing went wrong, but the row ends 2 pixels early, so the answer isSHORT BY 2.
Constraints
1 <= width <= 3000 <= row.length <= 400rowcontains only digits and uppercase lettersA-Z