Search code examples
iosobjective-crandomarc4random

using arc4random does not place images as "random" as I would like


I would like the images to appear more randomly than they do with this code:

//placing images on the screen
-(void)PlaceImage {

    RandomImagePosition = arc4random() %1000;
    Image.center = CGPointMake(570,  RandomImagePosition);

    // the higher the number (570) the farther to the right the platforms appear
}

They appear in different positions but most of the time towards to top of the screen. There will be a few times when the image is placed towards the bottom of the screen. I would like there to be more randomness.


Solution

  • Use arc4random_uniform to generate a random integer in a specified range. Never use arc4random mod something; that is indeed biased and will produce suboptimal results.

    If you have further issues with "randomness" the you should look carefully at how you are using your random value. Notably, people's perceptions of "random" are often quite different from mathematical random: for instance, people expect "random" coin flips to switch between heads and tails much more frequently than actual random will produce. Therefore, to make something perceptually random, you may have to fudge the output a bit (e.g. to reduce the chance that a value will repeat twice).