我想使用这个算法从字符串中选择一个随机单词:
选择概率为1:1的第一个单词,
选择概率为1:2的第二个单词,
选择概率为1的第n个单词:n
其中每个选择都会覆盖上一个选择。
我想使用std::mt19937来表示“随机性”。(有没有更好的方法?)
我的函数应该获得如下格式的inputstring:
word1 word2
word3 word4 word5
word6其中每行的字数是未指定的,并且用空格或换行符将单词彼此隔开。
这是std::mt19937的正确用法吗?
std::string random_word_from_string(std::string input)
{
static auto gen = std::mt19937{std::random_device{}()};
std::string random_word="";
std::string word="";
std::stringstream iss(input);
auto count = 0u;
while (iss >> word)
{
if (std::uniform_int_distribution{0u,count++}(gen) == 0)
{
random_word = word;
}
}
return random_word;
}如果这个问题已经在c++中得到了回答,很抱歉,但我找不到它!但我非常感谢你给了我这个复制品的链接。
发布于 2020-02-22 01:35:32
You can run the following program online:
#include <iostream>
#include <vector>
#include <random>
std::string GetRandomString(int seed, const std::vector<std::string>& StrVector)
{
std::mt19937 mt(seed);
std::uniform_real_distribution<double> dist(0.0, 100.0);
std::string ResultString= "";
for(int i=0; i< (int) StrVector.size(); ++i)
{
if(dist(mt) < 100.0/(i+1))
ResultString = StrVector[i];
}
return ResultString;
}
int main()
{
std::vector<std::string> StrVector;
StrVector.push_back("Hello");
StrVector.push_back("my");
StrVector.push_back("name");
StrVector.push_back("is");
StrVector.push_back("Bob");
std::cout << GetRandomString(0, StrVector) << std::endl;
std::cout << GetRandomString(1, StrVector) << std::endl;
std::cout << GetRandomString(2, StrVector) << std::endl;
std::cout << GetRandomString(3, StrVector) << std::endl;
std::cout << GetRandomString(4, StrVector) << std::endl;
}这条线
if(dist(mt) < 100.0/(i+1))确保按照您所描述的方式选择概率。
输出为:
Hello
name
Hello
name
myhttps://stackoverflow.com/questions/60342946
复制相似问题