Your task – should you choose to accept it – is to build a program that parses and evaluates a string (from left to right and of arbitrary length) of tokens that give directions – either left or right. Here are the four possible tokens and their meanings:
> go right one single step
< go left one single step
-> go right the total amount of single steps that you've gone right, plus one,
before you previously encountered this token and reset this counter to zero
<- go left the total amount of single steps that you've gone left, plus one,
before you previously encountered this token and reset this counter to zero
There's a catch though – the tokens of directions your program should be able to parse will be presented in this form:
<<->-><<->->>->>->
... in other words, they are concatenated, and it is your program's task to figure out the correct precedence of directions and amount of steps to take (by looking ahead). The order of precedence is as follows (from highest to lowest precedence):
->
<-
>
<
If you encounter <-
when no steps to the left had previously been made since either the start or since the last reset, take one single step to the left. Same rule applies to ->
, but then for going to the right.
Your program should start at 0 and its result should be a signed integer representing the final end position.
You may expect the input to always be valid (so, nothing like <--->>--<
, for instance).
Example input:
><->><-<-><-<>>->
Steps in this example:
step | token | amount | end position
------+-------+--------+--------------
1. | > | +1 | 1
2. | < | -1 | 0
3. | -> | +2 | 2
4. | > | +1 | 3
5. | <- | -2 | 1
6. | < | -1 | 0
7. | -> | +2 | 2
8. | <- | -2 | 0
9. | < | -1 | -1
10. | > | +1 | 0
11. | > | +1 | 1
12. | -> | +3 | 4
For clarification: the output of the program should only be the final end position as a signed integer. The table above is just there to illustrate the steps my example took. No need to output such a table, table row, or even just the steps' end positions. Only the final end position, as a signed integer, is required.
Shortest code, after one week, wins.
<-
is if it is immediately followed by a<
or a->
. There's no way in this language to represent the sequence<-
then>
- which would bego left the total amount of single steps that you've gone left, plus one, then go right one single step
. Is this correct and by design? \$\endgroup\$