Problem 4 solved in JavaScript