Today we will read on this article – Random pick with weight in C ++: If we have an array of positive integers, w [i] describes the weight of the index, we have to define a function pickIndex (), Which randomly chooses an index in proportion to its weight.
Example
#include <bits/stdc++.h> using namespace std; class program{ public: int n; vector <int> v; Solution(vector<int>& w) { srand(time(NULL)); n = w[0]; for(int i = 1; i < w.size(); i++){ w[i] += w[i - 1]; n = w[i]; } v = w; } int pickIndex() { return upper_bound(v.begin(), v.end(), rand() % v.back()) - v.begin(); } }; main(){ vector<int> v = {1,3}; Solution ob(v); cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; }
Input
Initialize with [1, 3] and call pickIndex five times.
Output
1 1 1 1 0