Question : How to choose numbers random with C?

Hi,

A number between 1 and 15 should be choosen random in C. The choice will be repeated 15 times in one game.

It should also be possible to repeat the game a few times without repeating a sequence.

In C I just know int rand(void). But I do not see the possibility to limit the numbers to be choosen from 1 to 15.

I also do not see the possibility to avoid the repetition of the numbers sequence for a few times.

Could somebody help me?

Many thanks and have a nice day!

Answer : How to choose numbers random with C?

>> In C I just know int rand(void).

That's a good start.

>> But I do not see the possibility to limit the numbers to be choosen from 1 to 15.

rand returns a number between 0 and RAND_MAX. If you want to limit the range to a pre-specified one, there's an easy way to do that. You can generate a random number between x and y (x inclusive) like this :

        x + (rand() % (y - x))

so, for values from 1 .. 15 :

        1 + (rand() % 15)

>> I also do not see the possibility to avoid the repetition of the numbers sequence for a few times.

If you don't want repetition, you'll have to keep track of the values that have already been generated, and if one is generated again, just generate another one.
Random Solutions  
 
programming4us programming4us