Made problem-31 more elegant and generic