Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Generating random vector

Tags:

c++

random

vector

I'm just starting out, trying to learn to program. So I'm programming in C++ for now, and I tried to create a function that will generate a vector of random integers based on the parameters. So my function so far looks like this:

std::vector<int> GenerateRandomVector(int NumberCount,int minimum, int maximum) {
    std::vector<int> vecRandomValues;
    int i = 0, randValue = 0;
    srand(time(NULL));
    while (i < NumberCount) {
        randValue = rand() % maximum + minimum;
        vecRandomValues.push_back(randValue);
        i++;
    }
    return vecRandomValues;
}

So, my problem is that it does not respect the minimum and maximum value I give it, and also most of the time, 40% of the generated numbers are 0. I cannot figure out what I did so wrong here, nor do I have any idea on how to fix it. I'm using Clion on Windows 10.

like image 580
Michael Bridge Avatar asked Mar 10 '26 16:03

Michael Bridge


2 Answers

To expand upon @Some programmer dude's comment:

std::vector<int> GenerateRandomVector(int NumberCount,int minimum, int maximum) {
    std::random_device rd; 
    std::mt19937 gen(rd()); // these can be global and/or static, depending on how you use random elsewhere

    std::vector<int> values(NumberCount); 
    std::uniform_int_distribution<> dis(minimum, maximum);
    std::generate(values.begin(), values.end(), [&](){ return dis(gen); });
    return values;
}
like image 88
Caleth Avatar answered Mar 13 '26 05:03

Caleth


Your computation for the range is wrong.

randValue = rand() % (maximum - minimum + 1) + minimum;
like image 34
acraig5075 Avatar answered Mar 13 '26 04:03

acraig5075



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!