Skip to content

Instantly share code, notes, and snippets.

@moritz
Created January 3, 2013 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/4445008 to your computer and use it in GitHub Desktop.
Save moritz/4445008 to your computer and use it in GitHub Desktop.
What's the expected loop length of a randomly chosen mapping from 1..N to 1..N?
use v6;
for 1..* -> $N {
my $sum = 0;
my $count = 5 * $N**2;
for ^$count {
my @f := (^$N).roll($N).list;
my %seen;
my $current = 0;
while !%seen{$current} {
%seen{$current} = True;
$current = @f[$current];
$sum++;
};
}
my $experiment = $sum / $count;
my $theory = theory($N);
FIRST say " N THEORY EXPERIMENT (ERR)";
printf "%3d %3f %3f (%2d%%)\n", $N, $theory, $experiment, abs($theory - $experiment) / $theory * 100;
}
sub postfix:<!>(Int $n) { [*] 1..$n }
sub theory($N) {
($N - 1)! * [+] (1..$N).map: {
$_ * $_ / $N ** $_ / ($N - $_)!
}
}
N THEORY EXPERIMENT (ERR)
1 1.000000 1.000000 ( 0%)
2 1.500000 1.550000 ( 3%)
3 1.888889 1.888889 ( 0%)
4 2.218750 2.137500 ( 3%)
5 2.510400 2.472000 ( 1%)
6 2.774691 2.733333 ( 1%)
7 3.018139 3.008163 ( 0%)
8 3.245018 3.356250 ( 3%)
9 3.458316 3.456790 ( 0%)
10 3.660216 3.628000 ( 0%)
11 3.852372 3.804959 ( 1%)
12 4.036074 3.962500 ( 1%)
13 4.212348 4.280473 ( 1%)
14 4.382029 4.355102 ( 0%)
15 4.545807 4.548444 ( 0%)
16 4.704258 4.683594 ( 0%)
17 4.857871 4.898962 ( 0%)
18 5.007063 5.041975 ( 0%)
19 5.152196 5.211080 ( 1%)
20 5.293585 5.314500 ( 0%)
21 5.431504 5.488435 ( 1%)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment