Scala solution for problem 2
Improved readability