mardi 6 octobre 2015

a new random vector with each call

I want generate a random vector including n elements in the range of min..max (in c++), 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.

Hope one of you has an idea on how to design this.

Best, Mario

#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: 359ms

1 0 10 8 3

1 0 10 8 3

Total execution time: 562ms




Aucun commentaire:

Enregistrer un commentaire