Pick Random Element from Stream with uniform probability

Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.

Example:

Input:  arr[]={22,44,33,55}
Output: 44 55 33 22 44 22 33 33 33 22 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int random_element(vector<int&stream)
{

    int size = stream.size();
    int rnd = rand() % size;
    return stream[rnd];
}

int main()
{
    vector<intstream = {22443355};
    for (int i = 0i < 10i++)
    {
        cout << random_element(stream<< " ";
    }
    return 0;
}


No comments:

Post a Comment