Refactored code for problem12