[sf-perl] randomize particular lines
Bart Alberti
bart at solozone.com
Mon Mar 6 17:54:48 PST 2006
Michael Budash wrote:
>On Mar 6, 2006, at 4:05 PM, Bart Alberti wrote:
>
>
>
>>Here is the idea I am working on.
>>Bart Alberti
>>
>>------------------------>>>>>>>>>>
>>
>>#!/usr/bin/perl
>>
>>
>
>
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];
}
}
More information about the SanFrancisco-pm
mailing list