MCPcopy Create free account
hub / github.com/WinVector/Logistic / ResevoirSampler

Class ResevoirSampler

src/com/winvector/util/ResevoirSampler.java:12–45  ·  view source on GitHub ↗

keep a uniform sample of items seen @author johnmount @param

Source from the content-addressed store, hash-verified

10 * @param <T>
11 */
12public final class ResevoirSampler<T> {
13 private final int maxSize;
14 private long nSeen = 0;
15 private final ArrayList<T> store;
16 private final Random rand;
17
18 public ResevoirSampler(final int maxSize, final long randSeed) {
19 this.maxSize = maxSize;
20 store = new ArrayList<T>(maxSize);
21 rand = new Random(randSeed);
22 }
23
24 public void observe(final T t) {
25 ++nSeen;
26 if(store.size()<maxSize) {
27 store.add(t);
28 } else {
29 // Invariant: if sampling were to stop right after this observation then this observation should be in the sample
30 // with odds exactly maxSize out of nSeen. Also using a uniform random selection from 0 through nSeen is also
31 // a uniform random selection from 0 through maxSize-1 when it happens to be less than maxSize.
32 long position = rand.nextLong()%nSeen;
33 if(position<0) {
34 position += nSeen;
35 }
36 if(position<store.size()) {
37 store.set((int)position,t);
38 }
39 }
40 }
41
42 public Iterable<T> data() {
43 return store;
44 }
45}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected