Solves #52 in scala