I want to use this algorithm for choosing a random word from a string:
Choose the first word with propability 1:1,
choose the second word with propability 1:2,
choose the nth word with propability 1:n
where each choice overwrites the last choice.
I want to use std::mt19937 for the "randomness". (is there a better method?)
My function should get an inputstring with this format:
word1 word2
word3 word4 word5
word6
where the number of words per line is unspecified, and words are seperated from eachother by blank spaces or new lines.
Is this the correct use of 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;
}
If this question is already answered in c++, sorry, but I wasn't able to find it! But I am very thankful for getting a link to the duplicate.
You can run the following program online:
The line
guarantees that the probability is chosen as you described.
The output reads: