Skip to main content
4 of 7
deleted 54 characters in body
George Reith
  • 2.5k
  • 1
  • 14
  • 16

#JavaScript, 138

z=l=r=0;c=["--z;++l;",/</g,"++z;++r;",/>/g,"z-=++l;l=0;",/<-/g,"z+=++r;r=0;",/->/g];for(a=8;a--;s=s.replace(c[a--],c[a]));eval(s);alert(z)

Unminified:

s="><->><-<-><-<>>->";
z=l=r=0;
c=[
    "--z;++l;", /</g,
    "++z;++r;", />/g,
    "z-=++l;l=0;", /<-/g,
    "z+=++r;r=0;", /->/g
];
for(a=8;a--;s=s.replace(c[a--],c[a]));
eval(s);
alert(z) // Output (4)

How it works

Given a string input as s like so:

s="><->><-<-><-<>>->";

It uses a Regex to replace each command with a set of instructions which modify z (the end position), l (stored left movements) and r stored right movements. Each Regex is performed in order of precedence.

For the input above this converts s to:

"++z;++r;--z;++l;z+=++r;r=0;++z;++r;z-=++l;l=0;--z;++l;z+=++r;r=0;z-=++l;l=0;--z;++l;++z;++r;++z;++r;z+=++r;r=0;"

Pretty, ain't it.

Finally we eval(s) to perform the instructions and alert z which contains the end position.

George Reith
  • 2.5k
  • 1
  • 14
  • 16