GNU sed, 8889 87 + 1(r flag) = 8988 bytes
Because sed has no integer types or arithmetic operations, the solution is arrived at by using regular expressions only.
s:$:65432Nx1:
:
/6x/!s:^U(.*)(.)x:\1x\2:
s:^D(.*)x(.):\1\2x:
t
s:[UD]U|D::
t
s:.*(.)x.*:\1:
It works by sliding the pointer x
based on each input shift, left (for U
p) or right (for D
own), along a non-wrapping tape that contains only the cells 65432N1
. The answer at the end is the value in the cell left of the pointer.
Example run: or Try it online!Try it online!
sed -rf gear.sed <<< "UUUUUUD"
5
Explanation:
s:$:65432Nx1: # assign initial tape and pointer
: # start loop
/6x/!s:^U(.*)(.)x:\1x\2: # if shift 'U', slide `x` to left, but not past the edge
s:^D(.*)x(.):\1\2x: # if shift 'D', slide `x` to right, -||-
t # repeat
s:[UD]U|D:: # if a shift couldn't be applied, delete it "manually",
t # and jump to the start of the loop again
s:.*(.)x.*:\1: # print value left of pointer `x` (answer)
I feel like there must be a shorter solution, I'll keep checking.