Why is that a favorite? I get it'll shuffle anything correctly, but trading O(NlogN) for O(1) is painful: #! perl -slw
use strict;
use Benchmark qw[ cmpthese ];
use List::Util qw[ shuffle ];
use Data::Dump qw[ pp ];
sub buk1 { $a = $_ + rand @_ - $_ , $b = $_[$_], $_[$_] = $_[$a], $_[$
+a] = $b for 0 .. $#_; return @_; }
sub buk2 {
die 'Need array reference' unless ref( $_[0] ) eq 'ARRAY';
our( @aliased, $a, $b ); local( *aliased, $a, $b ) = $_[0];
$a = $_ + rand @aliased - $_,
$b = $aliased[ $_ ],
$aliased[ $_ ] = $aliased[ $a ],
$aliased[ $a ] = $b
for 0 .. $#aliased;
return;
}
sub tybalt {
map $_->[0],
sort { $a->[1] <=> $b->[1] }
map [ $_, rand ], @_;
}
our $SANITY //= 0;
if( $SANITY ){
my %tests;
my @test = 1 .. 4;
buk2( \@test ),
++$tests{ buk2 }{ join ' ', @test } for 1 .. 10000;
++$tests{ buk1 }{ join ' ', buk1( @test ) } for 1 .. 10000;
++$tests{ tybalt }{ join ' ', tybalt( @test ) } for 1 .. 10000;
++$tests{ ListUtil }{ join ' ', shuffle( @test ) } for 1 .. 10000;
pp \%tests;
}
our $SIZE //= 100;
our @array = 1 .. $SIZE;
cmpthese -1, {
buk1 => q[ my @shuf = buk1( @array ); ],
buk2 => q[ buk2( \@array ) ],
tybalt => q[ my @shuf = tybalt( @array ); ],
ListUtil=> q[ my @shuf = shuffle( @array ); ],
}
Benchmark:
Rate tybalt buk1 buk2 ListUtil
tybalt 224/s -- -65% -70% -97%
buk1 644/s 187% -- -14% -91%
buk2 746/s 233% 16% -- -90%
ListUtil 7342/s 3176% 1040% 884% --
C:\test>shufflesBenchmark2018.pl -SIZE=1e3
Rate tybalt buk1 buk2 ListUtil
tybalt 229/s -- -66% -70% -97%
buk1 675/s 195% -- -13% -91%
buk2 776/s 238% 15% -- -89%
ListUtil 7339/s 3102% 987% 846% --
C:\test>shufflesBenchmark2018.pl -SIZE=1e4
Rate tybalt buk1 buk2 ListUtil
tybalt 17.2/s -- -75% -78% -98%
buk1 67.5/s 292% -- -13% -90%
buk2 77.2/s 349% 14% -- -89%
ListUtil 704/s 3992% 944% 812% --
C:\test>shufflesBenchmark2018.pl -SIZE=1e5
(warning: too few iterations for a reliable count)
Rate tybalt buk1 buk2 ListUtil
tybalt 1.21/s -- -81% -84% -98%
buk1 6.40/s 430% -- -15% -89%
buk2 7.53/s 523% 18% -- -87%
ListUtil 56.4/s 4566% 781% 649% --
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
In the absence of evidence, opinion is indistinguishable from prejudice.
Suck that fhit
| [reply] [d/l] [select] |
print "enter sequence and signal end with enter followed by ctrl d\n"
+;
$sequence = <STDIN>;
chomp $sequence;
print "sequence inserted : $sequence\n";
@trips = unpack("a3" x (length($sequence)-2), $sequence);
@trips = join(" ", @trips);
my @shuftrips = &myshuffle( @trips );
print "@shuftrips\n";
sub myshuffle
{
map $_->[0],
sort { $a->[1] <=> $b->[1] }
map [ $_, rand ], @_;
}
| [reply] [d/l] |
| [reply] [d/l] |