langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,18 @@
constant MAX_N = 20;
constant TRIALS = 100;
for 1 .. MAX_N -> $N {
my $empiric = TRIALS R/ [+] find-loop(random-mapping($N)).elems xx TRIALS;
my $theoric = [+]
map -> $k { $N ** ($k + 1) R/ [*] $k**2, $N - $k + 1 .. $N }, 1 .. $N;
FIRST say " N empiric theoric (error)";
FIRST say "=== ========= ============ =========";
printf "%3d %9.4f %12.4f (%4.2f%%)\n",
$N, $empiric,
$theoric, 100 * abs($theoric - $empiric) / $theoric;
}
sub random-mapping { hash .list Z=> .roll given ^$^size }
sub find-loop { 0, %^mapping{*} ...^ { (state %){$_}++ } }

View file

@ -0,0 +1,39 @@
link printf, factors
$define MAX_N 20
$define TIMES 1000000
$define RAND_MAX 2147483647
procedure expected(n)
local sum := 0
every i := 1 to n do
sum +:= factorial(n) / (n ^ i) / factorial(n - i)
return sum
end
procedure test(n, times)
local i, count := 0, x, bits
every i := 0 to times-1 do {
x := 1
bits := 0
while iand(bits, x)=0 do {
count +:= 1
bits := ior(bits, x)
x := ishift(1 , ?n-1)
}
}
return count
end
procedure main(void)
local n, cnt, avg, theory, diff
write(" n\tavg\texp.\tdiff\n", repl("-",29))
every n := 1 to MAX_N do {
cnt := test(n, TIMES)
avg := real(cnt) / TIMES
theory := expected(n)
diff := (avg / theory - 1) * 100
printf("%2d %8.4r %8.4r %6.3r%%\n", n, avg, theory, diff)
}
return 0
end