Improving and optimizing code for random generation