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 Index in C++
Suppose we have an array of integers with possible duplicates, we have to pick the index randomly of a given target number. We can assume that the given target number must exist in the array. So if the array is like [1,2,3,3,3], then pick(3), may return 2, 3, 4 randomly.
To solve this, we will follow these steps −
ret := - 1, cnt := 1
-
for i in range 0 to size of v
-
if v[i] = target, then
if random number mod cnt = 0, then ret = i
cnt := cnt + 1
-
return ret
Example (C++)
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector <int> v;
Solution(vector<int>& nums) {
srand(time(NULL));
v = nums;
}
int pick(int target) {
int ret = -1;
int cnt = 1;
for(int i = 0; i < v.size(); i++){
if(v[i] == target){
if(rand() % cnt++ == 0) ret = i;
}
}
return ret;
}
};
main(){
vector<int> v = {1,2,3,3,3};
Solution ob(v);
cout << (ob.pick(3));
}
Input
Initialize with [1,2,3,3,3] Call pick(3) to get random index positions
Output
4 3 4 2
Advertisements