Solve #123 in scala