This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -0,0 +1,19 @@
(defn s-of-n-fn-creator [n]
(fn [[sample iprev] item]
(let [i (inc iprev)]
(if (<= i n)
[(conj sample item) i]
(let [r (rand-int i)]
(if (< r n)
[(assoc sample r item) i]
[sample i]))))))
(def s-of-3-fn (s-of-n-fn-creator 3))
(->> #(reduce s-of-3-fn [[] 0] (range 10))
(repeatedly 100000)
(map first)
flatten
frequencies
sort
println)

View file

@ -0,0 +1 @@
([0 29924] [1 30053] [2 30018] [3 29765] [4 29974] [5 30225] [6 30082] [7 29996] [8 30128] [9 29835])

View file

@ -0,0 +1,5 @@
(defn s-of-n-creator [n]
(let [state (atom [[] 0])
s-of-n-fn (s-of-n-fn-creator n)]
(fn [item]
(first (swap! state s-of-n-fn item)))))

View file

@ -1,15 +1,20 @@
import std.stdio, std.random, std.algorithm;
struct SOfN(int n) {
double random01(ref Xorshift rng) {
immutable r = rng.front / cast(double)rng.max;
rng.popFront;
return r;
}
struct SOfN(size_t n) {
size_t i;
int[n] sample = void;
static rng = Xorshift(0);
int[] next(in int item) {
int[] next(in size_t item, ref Xorshift rng) {
i++;
if (i <= n)
sample[i - 1] = item;
else if (uniform(0.0, 1.0, rng) < (cast(double)n / i))
else if (rng.random01 < (cast(double)n / i))
sample[uniform(0, n, rng)] = item;
return sample[0 .. min(i, $)];
}
@ -18,12 +23,13 @@ struct SOfN(int n) {
void main() {
enum nRuns = 100_000;
size_t[10] bin;
auto rng = Xorshift(0);
foreach (trial; 0 .. nRuns) {
SOfN!(3) sofn;
foreach (item; 0 .. bin.length - 1)
sofn.next(item);
foreach (s; sofn.next(bin.length - 1))
foreach (immutable trial; 0 .. nRuns) {
SOfN!3 sofn;
foreach (immutable item; 0 .. bin.length - 1)
sofn.next(item, rng);
foreach (immutable s; sofn.next(bin.length - 1, rng))
bin[s]++;
}
writefln("Item counts for %d runs:\n%s", nRuns, bin);