| 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; |