
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Random Pick with Weight in C++
Suppose we have an array w of positive integers, were w[i] describes the weight of index i, we have to define a function pickIndex() which randomly picks an index in proportion to its weight.
So if the input is like [1,3], call pickIndex() five times, then the answer may come as − 0, 1, 1, 1, 0.
To solve this, we will follow these steps −
- Define an array v,
- Through the initializer, initialize as
- n := w[0]
- for i in range 1 to size of w
- w[i] := w[i] + w[i – 1]
- n := w[i]
- v = w
- The pickIndex() will work as follows −
- Take a random number r, perform r mod last element of v
- take the smallest number, not smaller than r from v, then subtract first number of v from the element and return.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { 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
Advertisements