RosettaCodeData/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-1.java

36 lines
868 B
Java
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
2018-08-17 15:15:24 +01:00
2013-04-10 21:29:02 -07:00
public SOfN(int _n) {
2018-08-17 15:15:24 +01:00
n = _n;
sample = new ArrayList<T>(n);
2013-04-10 21:29:02 -07:00
}
2018-08-17 15:15:24 +01:00
2013-04-10 21:29:02 -07:00
public List<T> process(T item) {
2018-08-17 15:15:24 +01:00
if (++i <= n) {
2013-04-10 21:29:02 -07:00
sample.add(item);
2018-08-17 15:15:24 +01:00
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
2013-04-10 21:29:02 -07:00
}
}
public class AlgorithmS {
public static void main(String[] args) {
2018-08-17 15:15:24 +01:00
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
2013-04-10 21:29:02 -07:00
}
}