random_shuffle not really random

前端 未结 3 1199
栀梦
栀梦 2020-12-20 15:31

I\'m using the random_shuffle on a vector like this:

#include 
vector  deck;
//some code to add cards to the deck h         


        
3条回答
  •  时光取名叫无心
    2020-12-20 16:29

    With current C++ (i.e. C++11) you can use the shuffle algorithm which can take a pseudo random number generator (PRNG) object (which you can seed) as third parameter:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main(int argc, char **argv)
    {
      vector v;
      for (int i = 1; i(time(0)));
      shuffle(v.begin(), v.end(), g);
      for (auto &x : v)
        cout << x << ' ';
      cout << '\n';
    }
    

    (for GCC 4.8.2 you need to compile it via g++ -std=c++11 -Wall -g shuffle.cc -o shuffle)

    In the above example, the PRNG is seeded with the current system time.

    For pre-C++11 compilers you only have the random_shuffle algorithm in the STL - but even with that you can optionally specify a number generator object/function to it. Note that you can't just pluck in a PRNG object like mtl19937 into it (because it does not provide a operator()(U upper_bound) member).

    Thus, you can supply your own adapter like this:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    struct Gen {
      mt19937 g;
      Gen()
       : g(static_cast(time(0)))
      {
      }
      size_t operator()(size_t n)
      {
        std::uniform_int_distribution d(0, n ? n-1 : 0);
        return d(g);
      }
    };
    
    int main(int argc, char **argv)
    {
      vector v;
      for (int i = 1; i::const_iterator i = v.begin(); i != v.end(); ++i)
        cout << *i << ' ';
      cout << '\n';
    }
    

提交回复
热议问题