Question

How do I generate a random number using the C4 Alpha Api?

Was it helpful?

Solution

In C4 you can use the C4Math class, which has a class-level method called randomInt...

[C4Math randomInt:255]; will give you a random number between 0 and 255.

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

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

Under the hood, these methods look like this:

+(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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top