^
1 N23456
+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
$1$2
.* (.).*
$1
Uses u
and d
for up and down.
Try it online!
Explanation
This program works by keeping 1N23456
behind the sequence of instructions. It keeps track of the current gear by having a space behind it. Then it takes one instruction at a time until there's no more.
^
1 N23456
Start by putting 1 N23456
before the input. The space before N
indicates that N
is the current gear.
+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
$1$2
These are two replacement stages, grouped together, and run until they stop changing the string:
(.)?(\w*6)u
$1 $2
The first one handles shifting the gear up. It will look for any number of gears after the space, followed by a 6
, then followed by u
(u
indicates the instruction to gear shift up). If there were characters before the 6, it swaps the space with the character immediately after it, deletes the u
, and leaves the rest of the string intact. Since the 6
is mandatory in the match, it will only swap the space with any character before the 6
. It will never swap with the 6
.
(.)? (\w*6)d
$1$2
The second stage handles gear shifting down, and works similarly. It looks optionally for a character before the space, then some other gears after ending in 6
, followed by d
. It swaps the space with the character before it, deletes the d
, and leaves the rest intact. If the space was at the start of the string, there was no match for a character before the space, so no swap occurs.
.* (.).*
$1
After neither of the above replacements can be done anymore, all gear shifts have been completed. The line is cleared of everything except the gear immediately after the space. This is the final gear.