Sync
This commit is contained in:
parent
6f050a029e
commit
776bba907c
3887 changed files with 59894 additions and 7280 deletions
19
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj
Normal file
19
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj
Normal 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)
|
||||
1
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj
Normal file
1
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj
Normal file
|
|
@ -0,0 +1 @@
|
|||
([0 29924] [1 30053] [2 30018] [3 29765] [4 29974] [5 30225] [6 30082] [7 29996] [8 30128] [9 29835])
|
||||
5
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj
Normal file
5
Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj
Normal 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)))))
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue