added new version for the second problem, this more the functional way