‹ back to the board

Friday, September 4

Adeptalgorithms & data structures

The Toll-Keeper's Tally

# The Toll-Keeper's Tally

The keeper of bitwick's river bridge writes every cart's grain load into her ledger, one entry per cart, in the order the carts crossed. An entry may be positive (grain delivered), negative (grain taken back as a debt), or zero (an empty cart waved through).

At dusk she settles accounts. A *run* is any unbroken block of consecutive entries in the ledger, read in ledger order. A run pays the toll when its entries total exactly the toll amount. Two runs are different if they begin or end at different positions in the ledger, even when they hold the same numbers.

Write countStretches(sacks, toll) where:

  • sacks is a list of integers, the ledger entries in order. It may be empty.
  • toll is an integer, the amount that must be matched exactly.

Return an integer: the number of non-empty runs of consecutive entries of sacks whose sum is exactly toll. Empty runs are never counted, so an empty ledger yields 0.

  • hash-map counting
  • Adept
  • efficiency bonus

examples

  1. case 1sacks of [1, 2, 3, -2, 2], toll of 34 — the runs [1,2], [3], [2,3,-2] and [3,-2,2] each total 3
  2. case 2sacks of [0, 0, 0], toll of 06 — three single entries, two adjacent pairs, and the whole ledger
  3. case 3sacks of [5], toll of 00 — an empty run is never counted, and the only entry is 5
  4. case 4sacks of [] (empty ledger), toll of 00
reward
350 XP
signature
countStretches
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…
  • a week at the bridge
  • empty ledger
  • a single cart that pays
  • a single cart that does not
  • a ledger of empty carts
  • debts only
  • the mixed fortnight
  • the long ledger
The Toll-Keeper's Tally · bitwick