Problem 2 solved in Javascript