簡體   English   中英

C ++隨機數生成不是隨機的

[英]c++ random number generation not 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]);
    }
}

我的問題是,當我連續多次調用此方法時,隨機播放不是隨機的。 代碼有什么問題?

任何幫助將非常感激。

嗯,我很好奇...以下內容不足以滿足您的需求:

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));
}

std::shuffle amountnt刪除重復項,它只是交換生成的隨機數的位置。

如何有效地從1到50中選擇幾個唯一的隨機數(不包括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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM