Online Random Sample

#1

Along the lines of solution code (with minor change to generate seed) while running this function, all of the tests fail. Is it a known issue?

vector OnlineRandomSample(vector::const_iterator stream_begin,
const vector::const_iterator stream_end,
int k) {
vector sample;
for(int i=0; i<k; ++i){
sample.emplace_back(*stream_begin++);
}

unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);

int num_seen = k;
while(stream_begin != stream_end){
int x = *stream_begin++;
num_seen++;
int index = std::uniform_int_distribution{0, num_seen-1}(generator);
if(index < k) {
sample[index] = x;
}
}
return sample;
}

0 Likes