Search code examples
c++randommersenne-twister

A new random vector with each call


I want generate a random vector including n elements in the range of [min,max], which works fine with the mersenne twister and my code below.

Obviously, every time I call my rand_vec function, I get the same output. But I need the random function to return different results each time I call it. Additionally, the whole process needs to be seeded, each time of execution the output has to be the same. So, seeding the twister in my function with std::random_device does not seem like a choice.

Also, this random function gets called from several subroutines of my program:

#include <iostream>
#include <vector>
#include <random>

std::vector<int> rand_vec(int n, int min, int max, std::mt19937 mt){

    std::vector<int> to_return(n);
    std::uniform_int_distribution<> my_dist(min, max);
    for(int i = 0; i < n; i++){
        to_return[i] = my_dist(mt);
    }
    return(to_return);
}

int main()
{
    std::vector<int> to_print(5);

    std::mt19937 mt;
    mt = std::mt19937(100);

    to_print = rand_vec(5, 0, 10, mt);
    for(int i = 0; i < 5; i++){
        std::cout << to_print[i] << " ";
    }

    std::cout << "\n\n";

    to_print = rand_vec(5, 0, 10, mt);
    for(int i = 0; i < 5; i++){
        std::cout << to_print[i] << " ";
    }

    std::cout << "\n\n";
}

Compiled with /EHsc /nologo /W4 main.cpp

Compilation successful! Total compilation time: 359 ms

1 0 10 8 3

1 0 10 8 3

Total execution time: 562 ms


Solution

  • You need to pass the random number generator by reference

    std::vector<int> rand_vec(int n, int min, int max, std::mt19937 mt)
    

    Should be

    std::vector<int> rand_vec(int n, int min, int max, std::mt19937 & mt)
    

    Otherwise you are reusing the same initial mt from main() which will start from the same spot giving you the same sequence.