‹ back to the board

Monday, October 5

Apprenticelogic & control flow

The Restless Chrysalis of Briarcombe

The Moth-Wardens of Briarcombe have caged a cursed chrysalis inside a chalk warding circle, and they pay well for anyone who can tell them what the coming nights will bring.

The chrysalis glows, and its glow is always a positive whole number. Each night the glow changes exactly once:

  • if the glow is even, it becomes half of itself;
  • if the glow is odd, it becomes three times itself plus one.

The creature inside wakes on the night the glow first equals exactly 1. The warding circle holds any glow up to and including ceiling. A glow strictly greater than ceiling breaks the circle.

Write chrysalisNights(start, ceiling).

  • start is tonight's glow, an integer.
  • ceiling is the circle's limit, an integer.
  • You may assume 1 <= start <= ceiling.

Return an integer: the number of nightly changes until the glow first equals 1. If any glow reached along the way is greater than ceiling before the glow reaches 1, return -1 instead. If start is already 1, return 0.

  • iterative sequence generation
  • Apprentice

examples

  1. case 1start of 6, ceiling of 168 (the glow runs 6, 3, 10, 5, 16, 8, 4, 2, 1; 16 equals the ceiling, so the circle holds)
  2. case 2start of 3, ceiling of 15-1 (the glow runs 3, 10, 5, 16, and 16 is above the ceiling)
  3. case 3start of 1, ceiling of 10 (the creature is already awake)
reward
220 XP
signature
chrysalisNights
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…
  • already awake
  • peak equals ceiling
  • breaks on fourth glow
  • seven held at exact peak
  • seven breaks one below peak
  • power of two straight down
  • long climb held
  • long climb breaks
  • two with generous ceiling
The Restless Chrysalis of Briarcombe · bitwick