Multiple random number generators in Objective C - objective-c

In my current project I need multiple random number generators because I need to be able to repeat their sequences independently from each other.
So far I did not find any way to achieve this with the standard objective-c random number generators, because they only have one global state.
I think having an random number generator class would solve my problem. I could create several instances which I could reset individually.
Is something like this already available? I was not able to find any random number generator implementation in objective c. I would like to avoid implementing it myself because I have no experience with random numbers and I think it is something that's hard to get right.

I have a random class, based on the Mersenne Twister algorithm, which you can get from my dropbox here.
It's rather old, and isn't compiled for ARC, but that doesn't make it any less good :)
Example code:
MTRandom *randWithSeed = [[MTRandom alloc] initWithSeed:12345];
double d = [rand nextDouble];
int i = [rand nextInt];
MTRandom *timeBasedRand = [MTRandom new]; // seeds with current time
double d2 = [timeBasedRand nextDouble];
int i2 = [timeBasedRand nextInt];
EDIT: If you want to be really cool, you can use this:
Source

Have you tried
srandom(seed);
and then calling
random();
? If the seeds are the same then you should get the same sequence of random numbers.

Related

arc4random initialisation

I am using random number generation as part of a procedure for minimising a function (using the Nelder-Mead simplex algorithm) in objective-c (for iOS). I have used arc4random() because it seems to be recommended everywhere on the grounds that a) it doesn't need to be seeded and b) it gives higher-quality random numbers than alternatives such as rand() and random(). I generate doubles between 0 and 1 using
#define ARC4RANDOM_MAX 0x100000000
-(double) Rnd{
return (double)arc4random() / (double)ARC4RANDOM_MAX ; }
However, to test the procedure I need to generate repeatable sequences of random numbers, and I can't find any reference to a way to initialise arc4random() to do this. Is it the case that arc4random() cannot be initialised to give a repeatable sequence? If so, how can anyone implement an automated unit test when every test will result in a different answer? Do I need to use the "lower quality" random numbers from random()? Thanks for your help.
The arc4random function gets random numbers from a pool over which it has no control. It has no mechanism to provide repeatability. For unit tests, you'll have to use something else.

How do I seed the rand() function in Objective-C?

Part of what I'm developing is a random company name generator. It draws from several arrays of name parts. I use the rand() function to draw the random name parts. However, the same "random" numbers are always generated in the same sequence every time I launch the app, so the same names always appear.
So I searched around SO, and in C there is an srand() function to "seed" the random function with something like the current time to make it more random - like srand(time(NULL)). Is there something like that for Objective-C that I can use for iOS development?
Why don't you use arc4random which doesn't require a seed? You use it like this:
int r = arc4random();
Here's an article comparing it to rand(). The arc4random() man page says this about it in comparison to rand():
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo-
random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and
random(3).
If you want a random number within a range, you can use the arc4random_uniform() function. For example, to generate a random number between 0 and 10, you would do this:
int i = arc4random_uniform(11);
Here's some info from the man page:
arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
The functions rand() and srand() are part of the Standard C Library and like the rest of the C library fully available for you to us in iOS development with Objective-C. Note that these routines have been superseded by random() and srandom(), which have almost identically calling conventions to rand() and srand() but produce much better results with a larger period. There is also an srandomdev() routine which initializes the state of the random number generator using the random number device. These are also part of the Standard C Library and available for use on iOS in Objective-C.

Why I keep getting the same random values? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
why do i always get the same sequence of random numbers with rand()?
I am confounded by the fact that even using different programs (on the same machine) to run /compile, and after nilling the vaues (before and after) the function.. that NO MATTER WHAT.. I'll keep getting the SAME "random" numbers… each and every time I run it. I swear this is NOT how it's supposed to work.. I'm going to illustrate as simply as is possible…
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
int rPrimitive = 0; rPrimitive = 1 + rand() % 50;
NSNumber *rObject = nil; rObject = [NSNumber numberWithInt:rand() % 10];
NSLog(#"%i %#", rPrimitive, rObject);
rPrimitive = 0; rObject = nil;
NSLog(#"%i %#", rPrimitive, rObject);
return 0;
}
Run it in TextMate:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
Run it in CodeRunner:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
Run it a million times, if you'd like. You can gues what it will always be. Why does this happen? Why oh why is this "how it is"?
This is why (from the rand man page):
If no seed value is provided, the rand() function is automatically
seeded with a value of 1.
Since it is always seeded with the same number it will always produce the same sequence of numbers. To get it to produce a different sequence each time it runs, you need to use a different seed each time it runs. You can use srand() to set the seed.
Because the numbers aren't random, they're pseudorandom. They're generated according to an algorithm which will always produce the same output, given the same initial seed. You're not seeding the PRNG, so it uses a default, constant seed.
If you seed the PRNG using something less predictable (such as the current time and/or PID), you will get different results each time. In the case of rand(3), you need to seed it with srand(3).
The reason it is like that is because rand is a pseudo-random-number-generator, meaning it doesn't generate true random numbers (which is actually a very difficult thing to do). It generates the next number in the sequence using the “seed”, and at the start of execution the seed is always set to the same value (1 or so), so if you don't change the seed, you'll always get the same sequence of random numbers. You can use something like srand(time(NULL)); to seed the random number generator based on the time, or you can use a random number generator that is considered strong enough for cryptographic purposes, arc4random.
You might thing “why is it like this?”, but there are some cases where you want to generate the same series of “random numbers” multiple times.

Nested arrays of methods/data

I have a question regarding nested arrays of objects.
I’m writing a simple objective c program (I’m a beginner) and I was wondering whether it is advisable to structure an array in such a way that not only are all the individual batting scores be logged (data), but also methods embedded in the nested arrays could be used to interrogate the this data.
For example the line below is easily readable (even for those who are not cricket fans!)
Team1.Over[2].BowlNumber[3].score = 6
Team 1 scored a 6 during the 3rd bowl in the 2nd Over.
I would also like to do something like the following where I can use a method to interrogate the data. The method line below would just cycle through the scores within BowNumber[] and total the scores up
Total =  Over[2].TotalForAmountForOver()
I could set up and manage all the arrays from within main() , but its much easier to read if I can embed as much as possible within the structure. 
Is this a common approach?
 
Haven't seen many examples of fairly complicated embedded arrays of data and methods…. 
You'd easily be able to achieve this by making Over cant Bowl classes that each wrap an NSMutableArray object. e.g.
- (void)getOverNumer:(int)index {
return [overs objectAtIndex:index];
}
You'd then access it like this:
[[team1 getOverNumber:2] getBowlNumber:2].score = 6;
int total = [[team1 getOverNumber:2] totalForAmountForOver];
You'd implement totalForAmountForOver as a method within your Over class.

Attach variables

I want to take two variables (in and in2) and put them together, for example:
in = 1;
in2 = 3;
pin = in.in2; // I want this to set pin to 13
The arduino IDE tells me that in is not a class, so what syntax would I use to accomplish this?
EDIT: I figured out a different way to do it, you can just take in. multiply it by 10 and then set pin to the sum of in plus in2
If your two variables are definitely integers then pin = (in*10)+in2; would work.
If not, read them into strings (maybe with in.toString(), language dependent) and just do pin = int.parse(in.toString()+in2.toString());
(Although, again dependent on language, you may have to do something other than int.parse [in C# you should use int.TryParse() for example])
Try this, I wrote it in C but you get the gist. turn the two items into strings then concatenate and parse it as an integer.
pin = int.Parse((string)in + (string)in2);