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<int> stream = {22, 44, 33, 55};
    for (int i = 0; i < 10; i++)
    {
        cout << random_element(stream) << " ";
    }
    return 0;
}


No comments:

Post a Comment