C++ & Qt: Don't pick a random number for x minutes -
let's have 10 numbers 1 10 , rand() picks number 3. number displayed on screen, but won't shown 15 minutes after picked. how can that?
i know srand should used better random results, that's not want achieve. want specific number shown once, after not appear until 15 minutes gone. i've read sleep, haven't figured out how works , if fits problem.
one straightforward way: keep record of numbers they're picked , time they're picked.
so each time want display number:
- check record , remove entries older 15 minutes.
- pick number between 1 , 10.
- check record see if picked number has been used in last fifteen minutes. if go step one.
- since picked number hasn't been used in last 15 minutes, display number.
- add new entry record picked number , current time.
note obviously, if pick 9 numbers in less 15 minutes, , tenth number picked within 15 minutes, result not random @ all. point being kind of constraint results less random more numbers picked within 15 minute window until there's no randomness left.
also, after 10 numbers have been picked in 15 minute window, there no numbers left, loop trying find number hasn't been picked spin until records removed. , have pick whatever number available. mean same sequence of numbers used every 15 minutes, on , over.
srand()
not function producing better random data rand()
. 2 functions work together: srand()
sets seed value used produce random sequence , rand()
produces values. srand()
doesn't produce better values or make rand()
produce 'better' values. allows select different sequence of values.
if want better, c++ <random>
header or perhaps third-party library.
the real benefit of c++ <random>
header distributions: instead of having figure out how produce random numbers (often using %
, bad idea), can use e.g. std::uniform_int_distribution<>(1, 10)
correctly produce number between 1 , 10.
#include <iostream> #include <random> int main() { // prepare reasonable source of randomness std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r()}; std::mt19937 prng(seed); // produce 50 random values between 1 , ten std::uniform_int_distribution<int> one_to_ten(1, 10); (int = 0; < 50; ++i) { std::cout << one_to_ten(prng) << "\n"; } }
Comments
Post a Comment