update repository
[cmdllinux.git] / bash_n_examples / perl / shuffle
blobd70500b2b32a6a80cf23b34291671bac27b171cb
1 #!/usr/bin/env perl
3 # Print input data in random order.
5 # TODO FYS algorithm works on in-memory array; way to shuffle while
6 # streaming over the input, similar to "print random line from file?"
7 # (shuf, apparently, if you have that toolset)
9 my @input = readline;
11 die "error: no data supplied to shuffle\n" unless @input;
13 fisher_yates_shuffle( \@input );
15 print for @input;
17 # fisher_yates_shuffle( \@array ) : generate a random permutation
18 # of @array in place
19 sub fisher_yates_shuffle {
20 my $array = shift;
21 my $i;
22 for ( $i = @$array; --$i; ) {
23 my $j = int rand( $i + 1 );
24 next if $i == $j;
25 @$array[ $i, $j ] = @$array[ $j, $i ];
29 END {
30 # Report problems when writing to stdout (perldoc perlopentut)
31 unless ( close(STDOUT) ) {
32 warn "error: problem closing STDOUT: $!\n";
33 exit 74;