【面试向】从洗牌算法说起

Fisher-Yates shuffle

Durstenfeld's in-place version

void FY_shuffle(vector<int>& a, int n) {
    default_random_engine e;
    // seed e
    for (int i = n - 1; i > 0; --i) {
        uniform_int_distribution<int> d(0, i);
        int index = d(e);
        swap(a[i], a[index]);
    }
}

现在问题是如何给随机数引擎 e 一个种子(seed)。常见的办法是用系统时间:std::time(nullptr) 或者 std::chrono::system_clock::now().time_since_epoch().count()。但是这种方法有争议,见 https://stackoverflow.com/q/36663027/6052725

Inside-out version

In this version, one successively places element number $i$ of the source array into a random position among the first $i$ positions in the target array, after moving the element previously occupying that position to position $i$.

void inside_out_shuffle(const vector<int>& source, vector<int>& a, int n) {
    default_random_engine e;
    // seed e
    a[0] = source[0];
    for (int i = 1; i < n; i++) {
        uniform_int_distribution<int> d(0, i);
        int index = d(e);
        if (index != i) {
            a[i] = a[index];
        }
        a[index] = source[i];
    }
}

转载于:https://www.cnblogs.com/Patt/p/11537531.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值