@Test public void reservoirSamplingSingleElement() { final List<Integer> a = Arrays.asList(0, 1); final int[] counts = new int[a.size()]; for (int i = 0; i < 10000000; i++) { final Optional<Integer> rrr = ReservoirSamplingSingleItem.reservoirSampling(a.iterator()); counts[rrr.get()]++; } System.out.println(Arrays.toString(counts)); }
public static <T> Optional<T> reservoirSampling(final Iterator<T> stream) { Optional<T> R = Optional.empty(); int k = 1; while (stream.hasNext()) { final T nextElement = stream.next(); final double pOfReplacement = 1.0 / (double) k; final double randomNumber = ThreadLocalRandom.current().nextDouble(); if (randomNumber < pOfReplacement) { R = Optional.of(nextElement); } k++; } return R; }
ReservoirSamplingSingleItem { public static <T> Optional<T> reservoirSampling(final Iterator<T> stream) { Optional<T> R = Optional.empty(); int k = 1; while (stream.hasNext()) { final T nextElement = stream.next(); final double pOfReplacement = 1.0 / (double) k; final double randomNumber = ThreadLocalRandom.current().nextDouble(); if (randomNumber < pOfReplacement) { R = Optional.of(nextElement); } k++; } return R; } }
ReservoirSamplingSingleItem { public static <T> Optional<T> reservoirSampling(final Iterator<T> stream) { Optional<T> R = Optional.empty(); int k = 1; while (stream.hasNext()) { final T nextElement = stream.next(); final double pOfReplacement = 1.0 / (double) k; final double randomNumber = ThreadLocalRandom.current().nextDouble(); if (randomNumber < pOfReplacement) { R = Optional.of(nextElement); } k++; } return R; }  }
ReservoirSamplingSingleItem { public static <T> Optional<T> reservoirSampling(final Iterator<T> stream) { Optional<T> R = Optional.empty(); int k = 1; while (stream.hasNext()) { final T nextElement = stream.next(); final double pOfReplacement = 1.0 / (double) k; final double randomNumber = ThreadLocalRandom.current().nextDouble(); if (randomNumber < pOfReplacement) { R = Optional.of(nextElement); } k++; } return R; }  static Optional<T> reservoirSampling(final Iterator<T> stream); }
ReservoirSamplingSingleItem { public static <T> Optional<T> reservoirSampling(final Iterator<T> stream) { Optional<T> R = Optional.empty(); int k = 1; while (stream.hasNext()) { final T nextElement = stream.next(); final double pOfReplacement = 1.0 / (double) k; final double randomNumber = ThreadLocalRandom.current().nextDouble(); if (randomNumber < pOfReplacement) { R = Optional.of(nextElement); } k++; } return R; }  static Optional<T> reservoirSampling(final Iterator<T> stream);  }