#368 · Games and puzzles · Advanced · 130 XP · about 25 min
You need exactly target litres of water, but all you have is a tap and two jugs with no markings: jug A holds a litres and jug B holds b litres. Both start empty. One step is one of these:
Write fewest_steps(a, b, target) that returns the fewest steps after which one of the jugs holds exactly target litres, 0 if target is 0, or -1 if it cannot be done.
fewest_steps(3, 5, 4) # returns 6 fewest_steps(2, 6, 5) # returns -1 fewest_steps(4, 9, 9) # returns 1
In the first example, writing the jugs as (A, B): fill B (0, 5), pour B into A (3, 2), empty A (0, 2), pour B into A (2, 0), fill B (2, 5), pour B into A (3, 4). B now holds 4 litres after 6 steps. In the second example every amount you can ever make is even.
First solves only, ranked by stars and then time.