1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <cstdlib> #include <ctime> #include <iostream> #include <vector>
std::vector<int> reservoirSampling(std::vector<int>& stream, int k) { std::vector<int> reservoir(k); int n = stream.size();
for (int i = 0; i < k; ++i) { reservoir[i] = stream[i]; }
for (int i = k; i < n; ++i) { int j = std::rand() % (i + 1);
if (j < k) { reservoir[j] = stream[i]; } }
return reservoir; }
int main() { std::srand(std::time(0));
std::vector<int> dataStream = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
std::vector<int> sampledData = reservoirSampling(dataStream, k);
std::cout << "Sampled Data: "; for (int i = 0; i < k; ++i) { std::cout << sampledData[i] << " "; } std::cout << std::endl;
return 0; }
|