C++ Boost random numeric generation problem -


i must generate random number using boost libraries, use code:

boost::mt19937 gen; boost::uniform_int<> dist(kuiminmanport, kuimaxmanport); boost::variate_generator< boost::mt19937&, boost::uniform_int<> > var(gen, dist); unsigned int value = (unsigned int)var(); return boost::lexical_cast<std::string>(value); 

obviously import necessary libraries. code compiles problem obtain same numbers....

ok ok... not worry, not such newbie when talking casual (or better pseudo-casual) number generation. know must provide seed , that, depending on seed, sequence of pseudocasual numbers provided.

so code becomes this:

boost::mt19937 gen(static_cast<unsigned int>(std::time(0))); boost::uniform_int<> dist(kuiminmanport, kuimaxmanport); boost::variate_generator< boost::mt19937&, boost::uniform_int<> > var(gen, dist); unsigned int value = (unsigned int)var(); return boost::lexical_cast<std::string>(value); 

well, problem same number everytime call function (inside cycle). suspect time depending seed provided generation core of boost random library not vary during period of time of cycle, that's why same number everytime run cycle , random number... question is: how solve problem in efficient way??? suppose best practice given... well, i'm not 1 having such problem :)

thanks...

static boost::mt19937 gen(static_cast<unsigned int>(std::time(0))); 

the static makes sure generator created once. problem time isn't changing fast enough. if call function in same millisecond, you'll exact same results. unfortunately, code fast you're calling in same millisecond.

making generator static (or singleton pattern, or global variable...) solve issue.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -