SHOW:
|
|
- or go back to the newest paste.
1 | #!/usr/bin/env perl | |
2 | ||
3 | use warnings; | |
4 | use strict; | |
5 | ||
6 | my @data = (1,2,3); | |
7 | my $trials = 1000000; | |
8 | ||
9 | my %results; | |
10 | ||
11 | my $shuffler = \&shuffle_listutil; | |
12 | #my $shuffler = \&shuffle_naive; | |
13 | #my $shuffler = \&shuffle_kfy; | |
14 | ||
15 | for (1..$trials) { | |
16 | $results{join '', $shuffler->(@data)}++; | |
17 | } | |
18 | ||
19 | for my $result (sort keys %results) { | |
20 | printf "%10s %.02f%%\n", $result, $results{$result}/$trials*100; | |
21 | } | |
22 | ||
23 | sub shuffle_listutil { | |
24 | require List::Util; | |
25 | return List::Util::shuffle(@_); | |
26 | } | |
27 | ||
28 | sub shuffle_naive { | |
29 | my @data = @_; | |
30 | for my $i (0..$#data) { | |
31 | my $n = int(rand($#data+1)); | |
32 | - | ($data[$i], $data[$n]) = ($data[$n], $data[$i]); |
32 | + | ($data[$i], $data[$n]) = ($data[$n], $data[$i]); |
33 | } | |
34 | return @data; | |
35 | } | |
36 | ||
37 | sub shuffle_kfy { | |
38 | my @data = @_; | |
39 | for my $i (0..$#data) { | |
40 | my $n = int(rand($#data-$i+1))+$i; | |
41 | - | ($data[$i], $data[$n]) = ($data[$n], $data[$i]); |
41 | + | ($data[$i], $data[$n]) = ($data[$n], $data[$i]); |
42 | } | |
43 | return @data; | |
44 | } | |
45 |