Skip to main content
1 of 3
seshoumara
  • 3.7k
  • 1
  • 13
  • 30

GNU sed, 88 + 1(r flag) = 89 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]::
t
s:.*(.)x.*:\1:

It works by sliding the pointer x based on each input shift, left (for Up) or right (for Down), along an 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!

sed -rf gear.sed <<< "UUUUUUD"
5

Explanation:

s:$:65432Nx1:              # initialize 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]::                   # if a shift couldn't be applied, delete it
t                          # jump to the start of the loop again
s:.*(.)x.*:\1:             # print value left of pointer `x` (answer)
seshoumara
  • 3.7k
  • 1
  • 13
  • 30