Random() % [employees count]


//Get a random number between 0 and 9 inclusive
NSUinteger randomIndex = random() % [employees count];

This is in the main.m file, near the end of chapter 19 in book. I dont quite understand how the random() function works in this line of code. How does this method call, that gets called each time the for loop executes know not to double up on previously seclected numbers between 0-9?

when calling [employees count], is it starting at 0 and incrementing by one with each loop?


Don’t have the book handy, but judging by that snippet there’s no such guarantee. If the random() algorithm is particularly bad, you could get the same result each loop.


hmm not only do I get the same results each time I run the app, but I get the exact sames output as in the book…guess it a pretty bad alogrithm then…


In order for random() to be random, it needs to be seeded. This code doesn’t do so.

That “feature” is useful for training books, since you can compare your output against the author’s. I don’t know if that was the motivation here.


You can seed it if you want to see different results each time you run it.

Near the beginning of main.m, add this line:



ahh cheers, that is very useful :slight_smile: