多种情况不同概率下,在范围内使用随机数。比如有5种情况,每种情况的概率不相同,有的概率为25,有的为15.
使用random库的函数来生成随机数。
std::random_device rd; //产生随机数种子
std::mt19937 gen(rd()); //生成伪随机数,使用rd作为种子
std::uniform_real_distribution<> dist(0, total_weight); //生成指定范围均匀分布的实数
int random_number = dist(gen); //调用均匀实数分布生成一个随机数
在五种概率情况下,通过生成随机数从五类中抽取一个随机结果。完整代码如下:
#include <iostream>
#include <random>
#include <vector>
enum EMoonCakePieceType {
E_PIECE_FLY = 0, // 碎片1
E_PIECE_LU = 1, // 碎片2
E_PIECE_CROSS = 2, // 碎片3
E_PIECE_MIDDLE = 3, // 碎片4
E_PIECE_AUTUMN = 4, // 碎片5
};
int main() {
std::random_device rd;
std::mt19937 gen(rd()); // 设置种子
// 每个字的概率
std::vector<std::pair<int, int>> words = {{E_PIECE_FLY, 15},
{E_PIECE_LU, 15},
{E_PIECE_CROSS, 25},
{E_PIECE_MIDDLE, 15},
{E_PIECE_AUTUMN, 30}};
// 计算总权重
int total_weight = 0;
for (std::vector<std::pair<int, int>>::const_iterator it = words.begin(); it != words.end(); ++it) {
total_weight += it->second;
}
std::vector<int> chinese;
std::uniform_real_distribution<> dist(0, total_weight);
int random_number = dist(gen);
int result_number = 4;
int cumulative_weight = 0;
for (std::vector<std::pair<int, int>>::iterator itb = words.begin(); itb != words.end(); ++itb) {
cumulative_weight += itb->second;
if (random_number <= cumulative_weight) {
result_number = itb->first;
break;
}
}
std::cout << result_number << std::endl;
chinese.push_back(result_number);
std::cout << "生成了:";
for (auto word: chinese) {
std::cout << word << " ";
} // 测试结果
std::cout << std::endl;
return 0;
}
开启个while循环测试多次运行,代码运行结果如下:
#include <iostream>
#include <random>
#include <vector>
#include <thread>
enum EMoonCakePieceType {
E_PIECE_FLY = 0, // 碎片1
E_PIECE_LU = 1, // 碎片2
E_PIECE_CROSS = 2, // 碎片3
E_PIECE_MIDDLE = 3, // 碎片4
E_PIECE_AUTUMN = 4, // 碎片5
};
int main() {
std::random_device rd;
std::mt19937 gen(rd()); // 设置种子
// 每个字的概率
std::vector<std::pair<int, int>> words = {{E_PIECE_FLY, 15},
{E_PIECE_LU, 15},
{E_PIECE_CROSS, 25},
{E_PIECE_MIDDLE, 15},
{E_PIECE_AUTUMN, 30}};
// 计算总权重
int total_weight = 0;
for (std::vector<std::pair<int, int>>::const_iterator it = words.begin(); it != words.end(); ++it) {
total_weight += it->second;
}
std::vector<int> chinese;
while (true) {
std::uniform_real_distribution<> dist(0, total_weight);
int random_number = dist(gen);
int result_number = 4;
int cumulative_weight = 0;
for (std::vector<std::pair<int, int>>::iterator itb = words.begin(); itb != words.end(); ++itb) {
cumulative_weight += itb->second;
if (random_number <= cumulative_weight) {
result_number = itb->first;
break;
}
}
std::cout << result_number << std::endl;
chinese.push_back(result_number);
std::cout << "生成了:";
for (auto word: chinese) {
std::cout << word << " ";
} // 测试结果
std::cout << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
return 0;
}
代码运行结果示例如下: