Solved problem 3 (with a perhaps ugly approach, but it works)