zoukankan      html  css  js  c++  java
  • 随机重拍与抽样(random_shuffle,random_sample,random_sample_n)

    random_shuffle

    1. 随机重排[first,last)中的数据,有N!中可能,N=last-first,此算法会产生一种均匀分布,任何特定排列顺序被选中的几率为1/N!,版本二是一种特别的function object,当被引数传进来,传递方式是by reference,而不是by value,因为RandomNumberGenerator的重要特点是具有局部状态,每次被调用时被改变。
    2. 使用乱数时,能够明白设定乱数产生器的种子是非常重要的,如果这对程序重要,则使用第二个版本。
    template <class RandomAccessIterator>                                             
    inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last)
    { 
        if(first != last)                                                             
            for(RandomAccessIterator i = first + 1; i != last; ++i)                   
                iter_swap(i, first + (rand() % ((i - first) + 1)));                   
    } 
    inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last,RandomNumberGenerator& rand)//by reference

    random_sample

    1. 随机的将[first,last)中的一个取样结果复制到[ofirst,olast)中,它会复制n个元素,n为min(last-first,olast-ofirst),Input range中的每个元素至多在Output range中出现一次,该结果以均匀方式选出
    2. 返回值为ofirst+n
    3. 对于N个元素,忽略元素顺序,欲选出n个元素,共有N!/(n!(N-n)!)中方法,本算法会产生均匀分布的结果,任何特定的元素被选出的几率为n/N,任何特定取样(不考虑元素顺序)几率为n!(N-n)!/N!
    4. 第一个版本用内部自定义的乱数产生器,第二个版本用自己定义的function object的乱数产生器
    5. Input range必须是Forward Iterator,Output range必须是RandomAccessIterator,所以Output range中元素的性对顺序不一定会与Input ragne中的顺序相同
    template <class InputerIterator,class RandomAccessIterator>
    RandomAccessIterator random_sample(InputerIterator first,InputIterator last,RandomAccessIterator ofirst,RandomAccessIterator olast);
    
    template <class InputerIterator,class RandomAccessIterator>
    RandomAccessIterator random_sample(InputerIterator first,InputIterator last,RandomAccessIterator ofirst,RandomAccessIterator olast,RandomNumberGenerator &rand);

    random_sample_n

    template <class InputerIterator,class OutputerIterator,class Distance>
    OutputerIterator random_sample_n(InputerIterator first,InputIterator last,OutputerIterator out,Distance n);
    
    template <class InputerIterator,class OutputerIterator,class Distance,class RandomNumberGenerator>
    OutputerIterator random_sample_n(InputerIterator first,InputIterator last,OutputerIterator out,Distance n,RandomNumberGenerator &rand);
    1. 从[first,last)中随机的复制元素到[out,out+n)中,他将复制m个元素,此处m为min(last-first,n),Input range中的每个元素至多在Output range中出现一次,该结果以均匀方式选出
    2. 返回值为out+m
    3. Input range必须是Forward Iterator,Output range必须是 Output Iterator,所以会保证两个容器中的相对顺序相同
  • 相关阅读:
    oracle中统计邮箱的总类
    java中形参的值传递
    There is no Action mapped for action name的解决方法
    java操作excel
    验证邮箱地址是否真实有效
    Tomcat服务器内外网通过IP地址都不能访问
    HashMap遍历的两种方式(转)
    用java实现栈
    oracle中利用merge语句防止重复插入
    sshkeyken 中文手册
  • 原文地址:https://www.cnblogs.com/tianzeng/p/10386217.html
Copyright © 2011-2022 走看看