-2

In c# i wrote a function that generates a next random number in the sequence using a random number generator which i seeded with a special value in the constructor:

    public randomS(int number = DefaultValue) : base(number)
    {
        seed = p;
        random = new Random((int) seed);

    }
    protected int GenerateNextSequence()
    {
       return random.Next(MIN_VALUE, MAX_VALUE);
    }

The user can then call a reset function to reset this sequence where i seed the random number generator again with the same value and the GenerateNextSequence will start generating the same numbers that it generated before the reset:

public override void ResetSequence()
    {
        random = new Random((int) seed);
        state = true;
    }

I would like to do the similar thing in C++. In not sure if its possible to do something like this in C++. If there is, could anyone help me?

  • Stack Overflow isn't a code translation service, sorry. Your question is _off-topic_, delete it please. – πάντα ῥεῖ Feb 16 '19 at 04:13
  • @Remy https://stackoverflow.com/questions/34490599/c11-how-to-set-seed-using-random – πάντα ῥεῖ Feb 16 '19 at 04:18
  • 2
    Which random number generator are you using in C++? If you are using the older [`std::rand()`](https://en.cppreference.com/w/cpp/numeric/random/rand) function then use [`std::srand()`](https://en.cppreference.com/w/cpp/numeric/random/srand). For the [newer C++ random-number classes](https://en.cppreference.com/w/cpp/numeric/random) in ``, the various "predefined random number generators" have a `seed()` method for re-seeding. – Remy Lebeau Feb 16 '19 at 04:21
  • Sorry, didn't mean to translate it literally. I just need help figuring out if there is something similar in c++. I am pretty new to c++ and Im still learning the language. – user11007400 Feb 16 '19 at 04:23

1 Answers1

0

You can seed the random number generator(e.g. std::mt19937) by calling obj.seed(value) cppref

To create 10 ints between 1~10:

#include <iostream>
#include <random>

class myrandom
{
public:
    int seed_;
    int min_ = 0, max_ = 10;

    std::mt19937 gen_; // random number generator
    std::uniform_int_distribution<int> dist_ {min_, max_}; // random number distribution

    // set a random seed if no argument provide
    myrandom (int seed = std::random_device{}()) { seed_ = seed; gen_.seed(seed); }
    int  get() { return dist_(gen_); }
    void reset () { gen_.seed(seed_); }
};

int main()
{
    myrandom randobj;

    for (int i=0; i<10; i++)
        std::cout << randobj.get() << " ";

    std::cout << "\n";
    randobj.reset();

    for (int i=0; i<10; i++)
        std::cout << randobj.get() << " ";
}

onlinegdb

hare1039
  • 310
  • 4
  • 10