dimanche 5 avril 2020

Best method of getting a random number at an "index" from a seed?

I was wanting to know a good way of getting a random number from an index. Basically, here is an example of what I want.

From what I know on how std::rand() / rand() works, it just gives you a random number each time it's called, and each time you reset a seed by calling std::srand it gives out the same exact numbers. But the way rand works seems very global, meaning that each time you call it, the number changes by some index of one from the original seed (I know that isn't exactly how it works under the hood though)

// User manually provides a seed, not by std::time(nullptr)
get_random(3); // Return 1641
get_random(67); // returns 2782
get_random(5); // return 9832
get_random(67); // return 2782

Notice that if I repeat an index, I still get the same result from the seed each time. I put a little bit of thought into it and this was my best result

int Class::get_random(int index) {
    std::srand(user_provided_seed); // reset the seed
    for (int i = 0; i < index; i++) {
        std::rand();
    }
    return std::rand();
}

The above works fine, basically it just expects a random number as an index and works with this number, but I feel like the above does a bit too much work, in my program I actually do expect the user to pass in a pretty large index, around the 1000s, and I feel like simply calling std::rand() 1000 times wastes CPU time.

Is there a better way to do this? Perhaps there is already a function included that does what I need it to. Also note that I do not need true random numbers and pseudo random numbers is perfect for my case.




Aucun commentaire:

Enregistrer un commentaire