gpt4 book ai didi

C++。加权 std::shuffle

转载 作者:可可西里 更新时间:2023-11-01 18:29:01 32 4
gpt4 key购买 nike

有没有一种方法可以使用标准库进行漂亮而优雅的加权洗牌?有 std::discrete_distribution。我想要的是这样的:

std::vector<T> data { N elements };
std::vector<int> weights { N weights };
std::shuffle(std::begin(data), std::end(data), something based on discrete distribution);

最佳答案

如果 OP 意图是洗牌 r 项列表

such that, given a list of weights w, the element a[i] with weight w[i] should be the first element of the random shuffle r with probability w[i]/sum(w).

page 中所述由 Severin Pappadeux 链接:

Weighted random shuffling is the same as weighted random sampling from a list a without replacement. That is, choose with probability w[i]/sum(w) element a[i] from a. Store this element in a list r. Then, remove element a[i] from a and w[i] from w, and select a new element of the modified list a, and so on until a is empty.

我不知道标准库中有这样的算法,但一个简单的实现可能是:

#include <random>
#include <algorithm>
#include <iterator>

template <class D, class W, class URBG>
void weighted_shuffle
( D first, D last
, W first_weight, W last_weight
, URBG&& g )
{
while (first != last and first_weight != last_weight)
{
std::discrete_distribution dd(first_weight, last_weight);
auto i = dd(g);
if ( i )
{
std::iter_swap(first, std::next(first, i));
std::iter_swap(first_weight, std::next(first_weight, i));
}
++first;
++first_weight;
}
}

实例HERE .

关于C++。加权 std::shuffle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221136/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com