hello!!
我是YR,一个闲的蛋疼的C++程序员
今天,我又开始闲的没事,
便打开洛谷,发现
我就想复刻这个简单的占卜系统
话不多说,上效果!
效果
怎么样?还不错吧,只要84行代码实现呦!
生成带权重的随机数
因为我们要随机用户的运势,但是不可能每种运势的几率都相等,所以需要生成带权重的随机数
看到这个需求,先百度一下
百度到了这个代码
#include <iostream>
#include <vector>
#include <numeric>
#include <ctime>
#include <cstdlib>
using std::vector;
using std::rand;
using std::srand;
using std::cout;
using std::endl;
class MyMath{
public:
vector<int> GetRandomNumWithWeight(vector<int> weight,int number){
int size = weight.size();
vector<int> res;
int accumulateValue = accumulate(weight.begin(),weight.end(),0);
srand(time(0));// srand()一定要放在循环外面或者是循环调用的外面,否则的话得到的是相同的随机数
for(int i = 0;i < number; i++)
{
int tempSum = 0;
int randomNnm = 0;
randomNnm = rand() % accumulateValue;
//0 ~ weight[0]为1,weight[0]+1 ~ weight[1]为2,依次类推
for(int j = 0;j < size;j++)
{
tempSum += weight[j];
cout << randomNnm << endl;
if(randomNnm <= tempSum)
{
res.push_back(j+1);
break;
}
}
}
return res;
}
};
int main()
{
vector&l