Random number c++ in some range

C++Random

C++ Problem Overview


> Possible Duplicate:
> Generate Random numbers uniformly over entire range

I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63.

How can I have that?

C++ Solutions


Solution 1 - C++

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

Solution 2 - C++

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

Solution 3 - C++

int range = max - min + 1;
int num = rand() % range + min;

Solution 4 - C++

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

Solution 5 - C++

Use the rand function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

Solution 6 - C++

float RandomFloat(float min, float max)
{
	float r = (float)rand() / (float)RAND_MAX;
	return min + r * (max - min);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbdul SamadView Question on Stackoverflow
Solution 1 - C++CubbiView Answer on Stackoverflow
Solution 2 - C++K-balloView Answer on Stackoverflow
Solution 3 - C++Benjamin LindleyView Answer on Stackoverflow
Solution 4 - C++NawazView Answer on Stackoverflow
Solution 5 - C++Kiley NaroView Answer on Stackoverflow
Solution 6 - C++Yurii HohanView Answer on Stackoverflow