[sf-perl] randomize particular lines
Michael Budash
mbudash at sonic.net
Tue Mar 7 00:46:35 PST 2006
On Mar 6, 2006, at 5:54 PM, Bart Alberti wrote:
> This produced only the first two lines of my 'dictionary' namely a
> list
> thus, without randomization of anything":
>
> bart at kissling:~/scramble/goodies> perl budash.pl
> ABRAHAM LINCOLN
> ABRAHAM LINCOLN by Carl Sandburg
> bart at kissling:~/scramble/goodies>
>
> the 'dictionary being as you can see simply a list of authors and
> works
> running 1600 lines
>
>
> Bart ALberti
>
> budash.pl is: -------->>>>>
> use strict;
> my $dictionary = 'textfile'; # 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];
> }
> }
hmm. can't imagine why...
More information about the SanFrancisco-pm
mailing list