Solved #6 in scala