‹ back to the board

Tuesday, September 29

Adeptalgorithms & data structures

The Toll-Book of Marrow Bridge

The keeper of Marrow Bridge writes one line in her toll-book for every day the bridge stands: coins taken that day, written as a positive number, or coins refunded to travellers turned back, written as a negative one. A quiet day is written as zero.

The town auditor has arrived with a figure in hand, and he wants to know how many runs of consecutive days in the book add up to exactly that figure.

Write tollTally(ledger, target).

  • ledger is a list of integers, in day order. Entries may be positive, negative, or zero, and the list may be empty.
  • target is an integer.

Return an integer: the number of non-empty runs of consecutive entries of ledger whose sum is exactly target. A run is chosen by its start and end positions, so two runs at different positions count separately even if they hold the same numbers. If no run qualifies, return 0.

  • hash-map counting
  • Adept

examples

  1. case 1ledger of [1, 2, 3, -1, 2], target of 52 — days 1 through 4 (1+2+3-1) and days 2 through 3 (2+3)
  2. case 2ledger of [0, 0, 0], target of 06 — three runs of one day, two of two days, one of three days
  3. case 3ledger of [], target of 00 — an empty book holds no runs at all
  4. case 4ledger of [7], target of 71
reward
320 XP
signature
tollTally
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…
  • mixed ledger with a refund
  • three quiet days, target zero
  • empty toll-book
  • single day that matches
  • single day that misses
  • heavy refunds
  • nothing adds up
  • alternating take and refund
  • negative target
The Toll-Book of Marrow Bridge · bitwick