Question

I am new to objective-c and I want to know the difference between these random number generators:

int randInt(int min, int max)
{
    return ((arc4random() % max) + min);
}

int randInt2(int min, int max)
{
    return (arc4random() % (max - min + 1)) + min;
}

int randInt3(int min, int max)
{
    return (arc4random_uniform(max) + min);
}

float randFloat(float min, float max)
{
    return (float)arc4random()/UINT32_MAX * (max - min) + min;
}

float randFloat2(float min, float max)
{
    return (float)arc4random_uniform(max)/UINT32_MAX * (max - min) + min;
}

In other words, I want to know why would someone choose randInt over randInt2 or vice-versa. Is randInt3 good?

I also want to know why I need to divide by UINT32_MAX for randFloat and whether or not I'm using the uniform versions of arc4random correctly.

Help?

Was it helpful?

Solution

randInt and randInt3 both give a value in the range "min to (max+min)". randInt3 is slightly better.

randInt2 gives a value in the range "min to max"

randFloat gives a value in the range "min to max" as a float.

randFloat2 is wrong and will always give a value in the range "min to (some really small number just above min".

The expression arc4random()/UINT32_MAX in randFloat gives a value in the range 0.0 to 1.0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top