Solve challenge 14.

This also replaces the solution to challenge 12 with a more general one.
The same code solves both 12 and 14.