Many of us are familiar with the game Tron. You control a "lightcycle" placed on a grid. The lightcycle always moves forward (though you control the direction) and leaves a permanent trail behind it. If you run into a trail, you crash!
The goal here is to determine if a given path is a valid loop, that is, it returns to its starting point without "crashing". To do this, we assume we start at the point (0,0)
. An input is given in the form N2E1S2W1
, with a series of cardinal directions (N
is north
, E
is east
, and so on), each followed by the distance to travel that direction. In this example, you would travel
N2 : North 2 to (0,2)
E1 : East 1 to (1,2)
S2 : South 2 to (1,0)
W1 : West 1 to (0,0)
A path is considered valid if it ends at (0,0)
without visiting any other coordinate more than once (it visits (0,0)
exactly twice. Once at the start, and once at the end). Keep in mind than in the above example, to get from (0,0)
to (0,2)
, we necessarily visit (0,1)
as well.
Other examples:
input -> output
N1E1S1W1 -> true
N1E1N1E1S2W2 -> true
N1S1E1W1 -> false // Visits (0,0) 3 times
N4E2S2W4S2E2 -> false // Visits (0,2) twice
N3E2S3 -> false // Does not return to (0,0)
N1S1 -> anything //I don't care how you evaluate this case
Your output can be in any form so long as it gives the same output for any truthy or falsey value.
The input can be taken as a string or as a list of characters, either in the form S1N2E3
... or SNNEEE
... There's is also no hard limit on the grid size, but assume the input isn't going to overflow anything. As long as the code is fundamentally sound, It's not crucial to handle cases like N99999999999999
.
NOTE: You may evaluate the cases N1S1
, E1W1
, S1N1
, and W1E1
however you would like. They're technically valid paths, but they go against the "Tron" spirit of the challenge.
Scoring
This is code-golf, so the shortest answer wins!
N1S1
should be true to be consistent with your definitions because it reaches(0, 0)
twice and(0, 1)
once, which is valid under your definition. \$\endgroup\$N
as1j
,E
as1
,S
as-1j
, andW
as-1
? \$\endgroup\$N99999999999999
\$\endgroup\$