此算法經常用於不知道總體規模有多大的時候,進行數據的抽樣,保證數據的公平性
public class ReservoirSamplingTest {
private int[] pool; // 所有數據
private final int N = 100000; // 數據規模
private Random random = new Random();
@Before
public void setUp() throws Exception {
// 初始化
pool = new int[N];
for (int i = 0; i < N; i++) {
pool[i] = i;
}
}
private int[] sampling(int K) {
int[] result = new int[K];
for (int i = 0; i < K; i++) { // 前 K 個元素直接放入數組中
result[i] = pool[i];
}
for (int i = K; i < N; i++) { // K + 1 個元素開始進行概率採樣
int r = random.nextInt(i + 1);
if (r < K) {
result[r] = pool[i];
}
}
return result;
}
@Test
public void test() throws Exception {
for (int i : sampling(100)) {
System.out.println(i);
}
}
}