[sf-perl] randomize particular lines

Michael Budash mbudash at sonic.net
Mon Mar 6 17:20:41 PST 2006


On Mar 6, 2006, at 4:05 PM, Bart Alberti wrote:

> Here is the idea I am working on.
> Bart Alberti
>
> ------------------------>>>>>>>>>>
>
> #!/usr/bin/perl
>
> #use warnings;
> use strict;
> my $dictionary = "textfile";
> my ($word);
>    open (DICT, $dictionary) or die "Cannot open $dictionary: $!";
>    my @words = <DICT>;
>    foreach (@words)
>    {
>     chomp($_);
>  #   print "$_,\n";  #for debug reason
>    }
>    if ($_ % 3 == 1){
>    $word = $words[rand @words];
>     my @scramble = split(//, $word);
>    @scramble = sort { (-1,1)[rand 2] } @scramble;
>   $word = $scramble; #if this line omitted, prints the whole file  
> unchanged
>   }
>     foreach (@words) {print "$_\n"};
> __END__

not very elegant, but this works for me: perhaps someone smarter than  
me can take the general idea and make it elegant...


use strict;

my $dictionary = '/usr/share/dict/words'; # mac os x

open (D, $dictionary) or die ("Can't open $dictionary: $!");

# store'em all in 3 alternating groups
my ($i, %lines);
foreach (<D>) {
         chomp;
         $i++;
         $i = 1 if $i == 4;
         push @{$lines{$i}}, $_;
}

close D;

# shuffle the third group
fisher_yates_shuffle( \@{$lines{3}} );

# re-join the three groups
my (@words, $last);
for my $g (0..(scalar(@{$lines{1}})-1)) {
         for my $l (1..3) {
                 if ($lines{$l}->[$g]) {
                         push @words, $lines{$l}->[$g];
                 }
                 else {
                         $last++;
                         last;
                 }
         }
         last if $last;
}

print "$_\n" foreach (@words);

#--------------------------------
sub fisher_yates_shuffle {
#--------------------------------
         my $deck = shift;  # $deck is a reference to an array
         my $i = @$deck;
         while ($i--) {
                 my $j = int rand ($i+1);
                 @$deck[$i,$j] = @$deck[$j,$i];
         }
}




More information about the SanFrancisco-pm mailing list