Apprenticelogic & control flow
The Amber Caravan's Salt Road
The Amber Caravan means to cross the Saltglass Waste, and the Guild of Dune-Pilots will pay for a reckoning of how far its water will carry it before anyone sets out.
The caravan's skins hold at most cap units of water, and it leaves the last well with them full. The road is a list legs of integers, walked in order from index 0:
- A leg with value
0or greater is a dry stretch. Crossing it costs exactly that many units of water. The caravan can cross it only if the water it is carrying is at least the leg's value. Water may fall to exactly0, and the caravan can still go on. - A leg with a negative value is a spring. Passing it adds the absolute value of that number to the water carried. The water carried never rises above
cap, and anything beyond that is lost.
Write firstStrandedLeg(cap, legs):
capis an integer,0or greater.legsis a list of integers, possibly empty.
Return the 0-based index of the first dry stretch the caravan does not have enough water to cross. If the caravan crosses every leg, return -1.
examples
- case 1
cap of 10, legs [2, -5, 11]2 (water goes 10, then 8, then the spring refills only up to 10, which is short of the 11 needed) - case 2
cap of 5, legs [2, 3, 0, -1, 1]-1 (water goes 5, 3, 0, 0, 1, 0; reaching exactly zero is allowed) - case 3
cap of 3, legs [4, 1]0 (the very first stretch is too long)
- reward
- 210 XP
- signature
firstStrandedLeg
TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.
loading the editor…
- spring capped at capacity strands the caravan
- reaching exactly zero still continues
- empty road
- first stretch too long
- zero capacity crosses zero-cost stretches only
- full crossing with a spring
- stranded late after several springs
- stranded one unit short