How to create a random number in C4? [C4Framework]

How to create a random number using C4 Alpha Api?

+3
source share
1 answer

In C4, you can use the C4Math class, which has a class method of the randomInt class ...

[C4Math randomInt:255]; will give you a random number from 0 to 255.

There is also a method randomIntBetweenA:andB:...

[C4Math randomIntBetweenA:100 andB:200] will give you randomInt between 100 and 200 ...

Under the hood, these methods are as follows:

+(NSInteger)randomInt:(NSInteger)value {
    srandomdev();
    return ((NSInteger)random())%value;
}

+(NSInteger)randomIntBetweenA:(NSInteger)a andB:(NSInteger)b{
    NSInteger returnVal;
    if (a == b) {
        returnVal = a;
    }
    else {
        NSInteger max = a > b ? a : b;
        NSInteger min = a < b ? a : b;
        NSAssert(max-min > 0, @"Your expression returned true for max-min <= 0 for some reason");
        srandomdev();
        returnVal = (((NSInteger)random())%(max-min) + min);
    }
    return returnVal;
}
+3
source

All Articles