Public Group

# random integers

This topic is 4790 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How do I assign an integer a random value?

##### Share on other sites
In what programming language?

C++, sorry.

##### Share on other sites

int n = rand();

?

Is that what you're referring to?

If so, make sure to set a new seed for the generator when you start the program or you'll always get the same random numbers. the seed usually comes in the form of the time.. either from when the operating system started, or real time of day.

##### Share on other sites
You can use the rand function.

common usage:

int RandomNumber;
RandomNumber = rand();

You might wish to "randomize" the randomizer. For this you need to 'seed' the randomizer.

common method:

srand((unsigned)time(NULL));

rand/srand - include stdlib.h
time - include time.h

HTH

##### Share on other sites
How to you confine it, for example, only give generate an integer between 1 and 10?

##### Share on other sites
The easiest way to do that is to use the modulus operator.

rand()%n gives a random number between 0 and n-1.

##### Share on other sites
Its the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).

##### Share on other sites
Quote:
 Original post by Anonymous PosterIts the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).

More important is that many implementations of rand() aren't very good. They favor the high order bits in terms of randomness, but the modulo method uses the low order bits. This is an issue for any value of n.

A better method is
min + (int)(max*rand()/(RAND_MAX+1.0));
Alternatively, you could use a different RNG. boost provides several good ones, including ways of drawing from a range without messing with silly formulas.

CM

##### Share on other sites

http://www.gamedev.net/community/forums/topic.asp?topic_id=157952
http://www.gamedev.net/community/forums/topic.asp?topic_id=219156

There are more, but you'll have to *search* for them ...

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633730
• Total Posts
3013580
×