refactored previous solution of problem 1