Skip to content

Instantly share code, notes, and snippets.

@XeroXP
Forked from albans/Sample.java
Created February 23, 2018 07:02
Show Gist options
  • Save XeroXP/2a6559cd83ad3a19cca92c8a9e66fee5 to your computer and use it in GitHub Desktop.
Save XeroXP/2a6559cd83ad3a19cca92c8a9e66fee5 to your computer and use it in GitHub Desktop.

Revisions

  1. @albans albans created this gist Apr 16, 2014.
    46 changes: 46 additions & 0 deletions Sample.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    import static java.util.Arrays.asList;

    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;

    import com.google.common.collect.AbstractIterator;

    public class Sample {
    public static <T> Iterator<T> sOfN(final Integer sampleSize, final Integer populationSize, final Iterator<T> populationItems) {
    return new AbstractIterator<T>() {
    Integer n = sampleSize;
    Integer N = populationSize;
    Integer t = 0;
    Integer m = 0;
    Random random = new Random();
    @Override
    protected T computeNext() {
    while (m<n) {
    T next = populationItems.next();
    double u = random.nextDouble();
    if ((N-t)*u >= n-m) {
    t++;
    } else {
    t++; m++;
    return next;
    }
    }
    return endOfData();
    }
    };
    }

    public static void main(String[] args) {
    int[] result = new int[10];
    List<Integer> digits = asList(0,1,2,3,4,5,6,7,8,9);
    for (int i=0; i<100000; i++) {
    Iterator<Integer> sample = Sample.sOfN(3, 10, digits.iterator());
    while(sample.hasNext()) {
    result[sample.next()]++;
    }
    }
    System.out.println(Arrays.toString(result));
    }
    }