Refactor random function