The Footprint Curse of Quellhaven Wood
The Wardens of Quellhaven Wood post this commission for any pathfinder willing to walk the old trails. The wood is laid out as a grid of clearings. A walker who steps into a clearing they have already stood in during the same walk is bound by the wood's curse at that moment. The Wardens want to know, for a planned route, exactly when that would happen.
The route is given as path, a string made only of the uppercase letters N, E, S and W. Each letter is one step to the neighbouring clearing:
Nmoves one clearing north.Smoves one clearing south.Emoves one clearing east.Wmoves one clearing west.
The walker begins in a starting clearing, and that clearing counts as already visited before the first step.
Write firstCrossing(path), which returns an integer: the number of the first step, counting from 1, that lands the walker in a clearing already visited earlier in the walk. Any steps after that one do not matter. If no step ever lands in an already-visited clearing, including when path is empty, return -1.
examples
- case 1
path of "NESW"4 (the fourth step returns to the starting clearing) - case 2
path of "NNESWW"5 (the fifth step re-enters the clearing reached by the first step) - case 3
path of "NNEE"-1 (every clearing is new) - case 4
path of "NS"2 (stepping straight back counts, since the start was already visited)
- reward
- 220 XP
- signature
firstCrossing
TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.
- loop back to start
- cross own trail mid-walk
- never repeats
- empty path
- immediate reversal
- single step
- stops early despite more moves
- negative coordinates
- long rectangle back to start
- straight line never repeats