Implementing a random oracle (the output is random in a range, but the output is the same for the same input) in C ++

I want to implement a random oracle in C ++. Essentially, a function f: {1, ..., n} → [0.1], so that for each input i in {1, ..., n} the output f (i) is a random value in [0 ,1]. But it is important that each call to the function f (i) return the same value.

In other words, I need a very large table f independently and identically distributed random variables [0,1] indexed by integers. Of course, I do not want prekompoputirovat table and store it. Instead, I want this table was realized "on the fly". You give input i, and you get the value from the table f (i).

What is the best way to implement it? One possibility is to use the input integer I, as seed for the random number generator. Then f (i) is a random number generated from the I as a seed. That's good enough? Thanks!

(This question has been edited based on helpful comments.)

+4
source share
1 answer

Instead, each time you call this function, create a new engine and a random distribution, you can use the following approach:

class F
{
    private:
       std::mt19937 generator;
       std::uniform_real_distribution<double> distribution; // choose your distribution here.
    public:
       F() : generator(), distribution(0, 1) {} // lower and upper bound here
       auto operator()(const size_t n) -> decltype(distribution(generator))
       {
          generator.seed(n);
          return distribution(generator);
       }
};

Using the trivial:

 int main()
 {
    F f;
    for ( size_t i(0); i < 10; ++i )
    {
       std::cout << f(i) << "\n";
    } 
 }

It generates a generator with a clearly defined number, and it is your, and then returns a value in this distribution.

+3
source