refactored random function