Random() % [employees count]


#1

//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?


#2

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.


#3

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…


#4

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.


#5

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:

srandom(time(NULL));


#6

ahh cheers, that is very useful :slight_smile: