#!/usr/bin/perl -w
# Read a file into an array.
# Find pairs of same integers and print these pairs and their positions.
# Finally, sort the indices by range and print a diagram.
# Written by Myst Shen in May,2008.
open (DATA, "data_file") || die "opening file: $!";
foreach (<DATA>){
push (@words, split);
}
close (DATA);
@words2 = @words;
$width = $#words;
$i = 0;
foreach $item (@words){
$i++;
if ( $item =~ /\d/ ){ for ( $j=0; $j<@words-$i; $j++ ) {
if ( $words[$i+$j] =~ /\d/ ) { if ( $words[$i+$j] == $item ){
$idx = $i+$j+1;
push (@arr1, "($item,$words[$i+$j])"); push (@arr2, "[$i,$idx]"); splice (@words, $i+$j, 1, "c");
last;
} }
}
}
}
sub by_range {
@aa = split (/\[|,|\]/,$a);
@bb = split (/\[|,|\]/,$b);
return ( $aa[2] - $aa[1] <=> $bb[2] - $bb[1] );
}
@arr3 = reverse (sort by_range @arr2);
print "The array is : \n";
print "@words2\n\n";
printf ("%d pairs found:\n",$#arr1 + 1);
print "@arr1\n\n";
print "The indices are:\n";
print "@arr2\n\n";
print "Sort the indices by range:\n";
print "@arr3\n\n";
print "Print a diagram: \n\n";
@pr = (" ");
for ( $m=0; $m<=$width; $m++ ) {
@pr = (" ", @pr);
}
for ( $n=0; $n<=$#arr1; $n++ ) { @aa = split (/\[|,|\]/, $arr3[0]);
@pr2 = @pr;
$line = "* " x ($aa[2]-$aa[1]+1);
splice (@pr2, $aa[1]-1, ($aa[2]-$aa[1])/2, $line);
print "@pr2\n";
shift @arr3;
}
print "@words2\n\n";
|