#JavaScript, 136
JavaScript, 136
z=0;l=r=1;c=["--z;++l;",/</g,"++z;++r;",/>/g,"z-=l;l=1;",/<-/g,"z+=r;r=1;",/->/g];for(a=8;a--;s=s.replace(c[a--],c[a]));eval(s);alert(z)
Unminified:
s="><->><-<-><-<>>->";
z=0;
l=r=1;
c=[
"--z;++l;", /</g,
"++z;++r;", />/g,
"z-=l;l=1;", /<-/g,
"z+=r;r=1;", /->/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=1;++z;++r;z-=l;l=1;--z;++l;z+=r;r=1;z-=l;l=1;--z;++l;++z;++r;++z;++r;z+=r;r=1;"
Pretty, ain't it.
Finally we eval(s)
to perform the instructions and alert z
which contains the end position.