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:


#7

NSUInteger randomIndex = random() % [employees count];

I’m tagging on to this thread hoping to get a response. TBH here’s what I do understand at a high level

We have a NSUInteger value called randomIndex

We are counting through an array employees to find how many members in it there

I am not clear what ‘%’ does in this line. Can someone please help break down this line?


#8

%, the modulus operator, ensures that the following constraint is satisfied:

randomIndex >= 0 and randomIndex < [employees count]

There is some math behind it:

// If m and N are integers, such that m >= 0 and N > 0
// then the expression m % N yields an integer r
// satisfying the constraint r >= 0 and r < N. 
// % is the modulus operator.

m = k * N + r // m >= 0, N > 0, k >= 0, r >= 0 and r < N.
m % N = r

Become a Competent Programmer


#9
>%, the modulus operator, ensures that the following constraint is satisfied:

randomIndex >= 0 and randomIndex < [employees count]

Thank you ibex10. The syntax for random() hadn’t been introduced in the book yet so this really helps.