Perl で配列をシャッフル
2006-11-28-2
[Programming]
Perl で配列をシャッフルする方法のメモ。
最近よく使うので。
Matthew McEachen :: Hints & Kinks :: shuffle in perl
http://matthew.mceachen.us/archives/000034.html
Recipe 4.17. Randomizing an Array (Perl Cookbook)
http://www.unix.org.ua/orelly/perl/cookbook/ch04_18.htm
行単位でシャッフルする簡単なスクリプト shuffle.pl を作ってみた。
最近よく使うので。
Matthew McEachen :: Hints & Kinks :: shuffle in perl
http://matthew.mceachen.us/archives/000034.html
use strict; use List::Util 'shuffle'; my @lines = <>; print shuffle( @lines );
Recipe 4.17. Randomizing an Array (Perl Cookbook)
http://www.unix.org.ua/orelly/perl/cookbook/ch04_18.htm
# fisher_yates_shuffle( \@array ) : generate a random permutation
# of @array in place
sub fisher_yates_shuffle {
my $array = shift;
my $i;
for ($i = @$array; --$i; ) {
my $j = int rand ($i+1);
next if $i == $j;
@$array[$i,$j] = @$array[$j,$i];
}
}
行単位でシャッフルする簡単なスクリプト shuffle.pl を作ってみた。
#!/usr/bin/perl use strict; use warnings; use List::Util 'shuffle'; my @results = (<>); print shuffle(@results);
