refactored random generator code to use a function.