# Use of random() in randomPossession

#1

Hi guys, first of all, thanks so much for having a dedicated forum for the book…makes the learning process a much better experience!

The question that I have is rather silly, and I feel like it’s something extremely obvious…but, since my brain is refusing to cooperate, I’m hoping someone can enlighten me. Why is it that building and running this app produces the EXACT same results (other than the creation date) as the example illustrated in the book? The name combination, serial numbers, and the dollar values are identical, and in the same order even though the random() function is being used. Am I missing something?

#2

Random numbers aren’t really “random” on a computer, they start with a seed number and perform some mathematical trickery to get a progression of “pseudorandom” numbers. Therefore, if you start with the same seed number, you always get the same numbers in the same order. (Unrelated, I’m sure you could write a “guess the number game” in which you knew the seed number and totally impress people with your future-seeing skills.)

If you want something that is “more random”, you should seed the random number generator with the function srandom(). You pass a number to this function. Typically, you pass the result of time(NULL) to this function so that you always have a brand new seed.

``````int main(...)
{
srandom(time(NULL));
....
}``````

#3

Ah ok, that’s what I was overlooking! I forgot about seeding the random number generator…totally makes sense now, thanks!

#4

May I ask a further question on this topic?

‘0’ + random() % 10

I’m OK with the random() % 10. This will return a “long” integer, either 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. But what happens then? How is a character plus integer interpreted?

David.

#5

‘0’ is the character 0, which has a value of something like 48. Assuming it is 48, ‘1’ is 49, ‘2’ is 50, and so on. Therefore, if we add the character ‘0’ to the random number generated, we get the character that represents that number.

#6

Since I’m VERY new at this, I couldn’t figure out how to use the information above to help me. After stumbling through some additional forums online, I managed to come up with this:

[ul]

• at the beginning of the section in Possession.m that sets all of the “ints” for “adjectiveIndex” and “nounIndex” add a line:
• srandomdev();
• this seeds a much more random number for every time the possession is created, and I now get truly unique names every time[/ul]

I ended up with this code:

``` // Get the index of a random adjective/noun from the lists // Note: the % operator, called the modulo operator, gives // you the remainder. So adjectiveIndex is a random number // from 0 to 2 inclusive, in this case. srandomdev(); int adjectiveIndex = random() % [randomAdjectiveList count]; int nounIndex = random() % [randomNounList count];```
I hope this helps someone else like me