c ++随机数生成不是随机的

时间:2014-05-27 08:47:08

标签: c++ random

我正在尝试使用Visual Studio 2013 C ++执行矢量的随机随机播放。以下是我的代码

    static void shuffle(vector<int>& a){
    int N = a.size();

    unsigned long long seed = chrono::system_clock::now().time_since_epoch().count();
    default_random_engine generator(seed);

    for (int i = 0; i < N; i++){
        uniform_int_distribution<int> distribution(0,(N-1)-i);
        int r = i + distribution(generator);
        swap(a[i], a[r]);
    }
}

我的问题是,当我连续多次调用此方法时,shuffle不是随机的。代码有什么问题?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

嗯,我很好奇......为什么以下内容不足以满足您的需求:

static void shuffle(vector<int>& a)
{
    // There are better options for a seed here, but this is what you used
    // in your example and it's not horrible, so we'll stick with it.
    auto seed (std::chrono::system_clock::now().time_since_epoch().count());

    // Don't bother writing code to swap the elements. Just ask the standard
    // library to shuffle the vector for us.
    std::shuffle(std::begin(a), std::end(a), std::default_random_engine(seed));
}

答案 1 :(得分:-1)

std::shuffle不删除重复项,只是交换生成的随机数的位置。

How can I efficiently select several unique random numbers from 1 to 50, excluding x?

你可以在家做自己的洗牌代码:

#include <ctime>
#include <string>
#include <vector>
#include <iostream>
using namespace std;


void myShuffleWithNoRepeats( int  random_once_buf[] , int size=100)
{
      srand(time(0));

      for (int i=0;i<size;i++)  
      {
          // call made to rand( ) , stored in random_once_buf[ ]
          random_once_buf[i]=rand() % 100;

          //////////////////////////////////////////////////////////////////////////////////////
          // The line below generates unique random number only once                          //
          //                                                                                  //
          // the variable i is the random_once_buffer[i] buffer array index count,            //
          // j is the check for duplicates, j goes through the random_once_buffer[i] buffer   //
          // from 0 to i at every iteration scanning for duplicates, reversing one step  if one duplicate is found..                         //
          //////////////////////////////////////////////////////////////////////////////////////

          for(int j=0;j<i;j++)  if (random_once_buf[j] == random_once_buf[i]) i--; 


      }
       cout<<"   \n\n\n ";

}



int main(void)
{

      const int size=100 ;
      int  random_once_buffer[100] ;


      // Call made to function myShuffleWithNoRepeats( )
      myShuffleWithNoRepeats( random_once_buffer , size );

      // Loop to display the array random_once_buffer[ ]
      for ( int i=0;i<size;i++) cout<<""<<random_once_buffer[i]<<"\t";

      cout<<" \nPress any key to continue\n";
      cin.ignore();
      cin.get();

  return 0;
}