‹ back to the board

Tuesday, September 29

Apprenticelogic & control flow

The Tollgates of Marrowmere

The road out of Marrowmere runs through a line of gatehouses. Some gates take a toll from a passing cart; others hand out a bounty from the town chest.

You are given three arguments:

  • purse — an integer, the coins the carter sets out with (0 <= purse <= cap).
  • cap — an integer, the most coins the purse can hold.
  • tolls — a list of integers, one per gatehouse, in the order they are met. A positive value is a toll charged; a value of zero or less is a bounty of that many coins paid to the carter (a value of 0 pays nothing).

The cart meets the gatehouses in order:

  • At a gate with a positive value v: if the purse holds at least v coins, v coins are paid out of the purse and the gate is passed. Otherwise the cart is turned back at once — that gate is not passed, and no later gate is reached.
  • At a gate with a value of zero or less: the bounty is added to the purse, and the gate is passed. If this would take the purse above cap, the purse is left holding exactly cap coins and the surplus is lost.

Write tollRun(purse, cap, tolls), which returns a list of exactly two integers: the number of gates passed, and the coins left in the purse when the journey ends.

  • loops with early exit
  • Apprentice

examples

  1. case 1purse of 10, cap of 12, tolls of [4, -5, 7, 3][4, 1] — pays 4 (6 left), takes a bounty of 5 (11), pays 7 (4), pays 3 (1); all four gates passed
  2. case 2purse of 3, cap of 6, tolls of [-9, 5, 2][2, 1] — the bounty of 9 would make 12, so the purse is left at 6; pays 5 (1 left); then 2 cannot be paid and the cart is turned back
  3. case 3purse of 5, cap of 5, tolls of [5, 1][1, 0] — the first toll takes exactly everything, so that gate is passed with an empty purse; the second gate turns the cart back
reward
200 XP
signature
tollRun
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…
  • no gates on the road
  • full run with a bounty
  • bounty spills over the cap, then turned back
  • exact change empties the purse
  • turned back at the very first gate
  • gates that pay nothing
  • purse already at the cap
The Tollgates of Marrowmere · bitwick