+ -
当前位置:首页 → 问答吧 → vc 的 rand() 问题

vc 的 rand() 问题

时间:2011-09-18

来源:互联网


用 VC 产生由 1,2 组成的伪随机数序列(序列长度为 30 )的程序为:

  int c[30];  
  srand((unsigned)time(NULL));
  for(int i=0;i<=29;i++)
 {
  c[ i ]=rand()%(2-1+1)+1;
 }



然后 来看所产生序列中连续出现 1 的最多个数。
比如,产生一个序列长度为 30, 由 1,2 组成的伪随机数序列:
1 2 2 1 2 1 1 2 1 1 1 1 1 2 1 1 2 1 1 2 1 2 1 1 1 2 2 1 2 1
则该序列中连续出现 1 的最多个数是 5 。


现在问题是始终得不到连续出现 16 个以上 1 的序列,请问问题出在哪里?(用 excel+vba 则很容易到,甚至可以得到 30 个元素都为 1 的序列)

作者: lkjhgf   发布时间: 2011-09-18

按概率对半,30个1/2序列,求连续出现16个1以上的序列的出现概率,大侠们动手了。

作者: fanster28_   发布时间: 2011-09-18

C/C++ code
bool judge(int* array, int threshold)
{
    int count = 1;
    int current = array[0];
    int max = -1;

    for (int i=1; i<30; i++)
    {
        if (array[i]==current)
            ++count;
        else
        {
            //if (count > max)
            //    max = count;

            if (count >= threshold)
                return true;

            count = 1;
            current = array[i];
        }
    }

    return false;
}
    int c[30] = {0};
    srand((unsigned)time(NULL));

    time_t begin = clock();
    while (1)
    {
        for(int i=0;i<30;i++)
        {
            c[ i ]=rand()%(2)+1;
        }

        copy(c, c+30, ostream_iterator<int>(cout, " "));
        cout << endl;

        if ( judge(c, 16) )
            break;
    }
    time_t end = clock();
    cout << "Time Costs :" <<  (end - begin) / 1000 << endl;

    // 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 2 2 2 2 1 1 2 2
    // Time Costs :4

    // 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 2 2 2 1 1 1 1 2 2
    // Time Costs :3

测试了一下,连续16个基本上不可能出现,可能跟rand函数实现有关,

作者: dizuo   发布时间: 2011-09-18

热门下载

更多