Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random numbers between 2 values, inclusive? [duplicate]

I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    int userBeg, userEnd, outPut;

    cout << "Enter a start value: ";
    cin >> userBeg;
    cout << "Enter an end value: ";
    cin >> userEnd;

    srand(time(NULL)); //generates random seed val

    for (int i = 0; i < 5; i++) {
      //prints number between user input, inclusive
    outPut = rand()%((userEnd - userBeg) + 1); 
    cout << outPut << "  ";
    }//end for

    return 0;
}//end main 

I'm confused with the output I get for the following ranges: 1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22. But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?

Thank you in advance for your help!

like image 930
bluthunder Avatar asked Dec 01 '22 12:12

bluthunder


2 Answers

Using the c++11 random library.

You could use std::default_random_engine (or any other random engine) with std::uniform_int_distribution.

The values you pass to std::uniform_int_distribution will be the lower and upper bounds of your random range.

e.g.

#include <iostream>
#include <random>

int main()
{
    const int nrolls = 100;

    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(0,9);

    int p[nrolls]={};

    for (int i=0; i<nrolls; ++i)
    {
        p[i] = distribution(generator);
    }

    std::cout << "uniform_int_distribution (0,9):" << '\n';
    for (int i=0; i<nrolls; ++i)
    {
        std::cout << i << ": " << p[i] << '\n';
    }
}

If you wish to seed the random engine, create it like.

unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

std::default_random_engine generator(seed);
like image 115
Paul Rooney Avatar answered Dec 04 '22 01:12

Paul Rooney


rand returns number between 0 and RAND_MAX. By taking modulo userEnd - userBeg + 1 the boundaries will be limited to 0 and userEnd - userBeg. If the random number should be within given boundaries, then userBeg should be added, so the calculus becomes

    outPut = rand()%((userEnd - userBeg) + 1) + userBeg; 
like image 30
karastojko Avatar answered Dec 04 '22 02:12

karastojko