Tricky Random Numbers in a Range
I’m working on a learn project to know more about Objective C, the Cocoa Framework and just for fun. I think only from the praxis I’ll be able to solve little problems that one does not have in the Theory.
Yesterday was the problem: how can I generate random numbers? and this within a range? well for the C/C++ people this wouldn’t be a problem. In fact one can use the same functions as in C/C++ but I thought there would be a more ‘cocoay’ version for that, like:
[NSNumber randomIntFrom:(int)a to:(int)b ];
Well, there is not such a thing. However, I knew I was able with a tutorial I made a couple of months ago, that random numbers was possible and with a very easy way, rather than calling random() or rand() an dividing and scaling, etc… I looked at an old ScreenSaver Tutorial and I found the answer there. I still was a little bit ‘disappointed’ there wasn’t like an NSValue or NSNumber that does this job, but well, the ScreenSaver framework has a fix for that…
#import <ScreenSaver/ScreenSaver.h>
SSRandomIntBetween(0, 100);
SSRandomFloatBetween(0.0, 1.0);
Well that was the kind of easy function I was looking for, but I couldn’t expect it to be in the ScreenSaver Framework!
Anyway it’s just a C function call that looks like this:
static __inline__ int SSRandomIntBetween(int a, int b)
{
int range = b – a < 0 ? b – a – 1 : b – a + 1;
int value = (int)(range * ((float) random() / (float) RAND_MAX));
return value == range ? a : a + value;
}
I think I’ll stay with the ScreenSaver solution, even if it isn’t beautiful to call a ScreenSaver function in your app, but well… it’s a lot more understandable and they made a much better and elegant solution than my first try. I guess one could copy also the code in that function and make it your own… but the ScreenSaver Framework has everybody so… why not use it? At least for little projects should do the job.