Working solution for Exercise 4 (+ algorithms from the book)