‹ back to the board

Thursday, October 15

Apprenticelogic & control flow

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:

  • N moves one clearing north.
  • S moves one clearing south.
  • E moves one clearing east.
  • W moves 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.

  • loops with early exit
  • Apprentice

examples

  1. case 1path of "NESW"4 (the fourth step returns to the starting clearing)
  2. case 2path of "NNESWW"5 (the fifth step re-enters the clearing reached by the first step)
  3. case 3path of "NNEE"-1 (every clearing is new)
  4. case 4path of "NS"2 (stepping straight back counts, since the start was already visited)
reward
220 XP
signature
firstCrossing
not yet run

TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.

loading the editor…
  • 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
The Footprint Curse of Quellhaven Wood · bitwick