‹ back to the board

Thursday, September 10

Apprenticelogic & control flow

The Ward-Stone of the Gatehouse

The gatehouse portcullis is held shut by a ward-lock, and the old ward-stone has cracked. The locksmith needs a new one cut.

A ward-stone is identified by a whole number. The quarry only sells stones numbered from start to limit, inclusive. For a stone to fit the lock, two things must hold of its number:

  • it is an exact multiple of step (the chisel spacing), and
  • the sum of its decimal digits equals target (the notches cut into the lock plate).

The locksmith pays by the number, so she wants the smallest fitting stone.

Write wardNumber(start, limit, step, target). All four arguments are integers, with 0 <= start <= limit, step >= 1, and target >= 0. Return the smallest integer n with start <= n <= limit that is a multiple of step and whose digits sum to target. If no number in the range satisfies both conditions, return -1.

  • bounded search
  • Apprentice

examples

  1. case 1start of 10, limit of 99, step of 7, target of 835 — the multiples of 7 in range begin 14, 21, 28, 35 with digit sums 5, 3, 10, 8, so 35 is the first that fits
  2. case 2start of 0, limit of 0, step of 5, target of 00 — zero is a multiple of 5 and its digits sum to 0
  3. case 3start of 1, limit of 20, step of 3, target of 11-1 — the multiples of 3 in range are 3, 6, 9, 12, 15, 18, whose digit sums are 3, 6, 9, 3, 6, 9
reward
200 XP
signature
wardNumber
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…
  • fourth multiple is the one that fits
  • zero is a valid ward-stone
  • no stone in the range fits
  • single-number range that fits
  • spacing larger than the whole range
  • every number allowed, heavy notching
  • search starts past the early matches
The Ward-Stone of the Gatehouse · bitwick