3

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

Randolpho
  • 55,384
  • 17
  • 145
  • 179
Greg Debicki
  • 235
  • 2
  • 6
  • possible duplicate of [Generating Random Numbers in Objective-C](http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c) – Randolpho Apr 30 '12 at 21:12
  • 1
    @MДΓΓ БДLL greg is asking about a framework called C4, which has a built in method for doing this... So, his question is valid. No need for the attitude. – C4 - Travis Apr 30 '12 at 21:24
  • @Randolpho Greg is referring to a framework called C4. There is a method for generating random numbers, but it isn't documented yet, so this isn't really a duplicate question. – C4 - Travis Apr 30 '12 at 21:33
  • @C4-Travis Fair enough. Looks like C4 is getting a fair number of questions on Stack Overflow, so I went ahead and added a C4 tag. – Randolpho Apr 30 '12 at 21:34
  • wicked! I don't have enough rep yet to do that... Thanks a lot. – C4 - Travis Apr 30 '12 at 21:51

1 Answers1

3

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;
}
C4 - Travis
  • 4,502
  • 4
  • 31
  • 56