生成具有权重的随机数。随机数ranIndex生成的区间为权重的总和,根据权重分割子区间。
//************************************ // Method: GetRandomNumWithWeight // Desc: 生成具有权重的随机数。随机数ranIndex生成的区间为权重的总和,根据权重分割子区间。 // Author: ljm // Date: 2019/07/18 // FullName: GetRandomNumWithWeight // Access: public // Returns: void // Qualifier: // Parameter: vector<int> weight :权重 // Parameter: int number :随机数数量 //************************************ void GetRandomNumWithWeight(vector<int> weight, int number) { int size = weight.size(); //计算权重的总和 int accumulateVal = accumulate(weight.begin(), weight.end(), 0); vector<int> res(number, 0); for (int i = 0; i < number; i++) { int tempSum = 0; int ranIndex = myRand(0, accumulateVal); //0 ~ weight[0]为1,weight[0]+1 ~ weight[1]为2,依次类推 for (int j = 0; j < size; j++) { tempSum += weight[j]; if (ranIndex <= tempSum + weight[j]) { res[i] = j + 1; break; } } } for (auto num : res) { cout << num << " "; } }测试
int main() { vector<int> weight = { 8000, 1000, 500, 10, 10, 10, 10, 10, 10, 10}; GetRandomNumWithWeight(weight, 3); }输出
1 1 1