Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1331662
  • 博文数量: 268
  • 博客积分: 10698
  • 博客等级: 上将
  • 技术积分: 2867
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-14 22:21
文章分类

全部博文(268)

文章存档

2012年(19)

2011年(13)

2010年(29)

2009年(26)

2008年(99)

2007年(82)

我的朋友

分类:

2008-05-16 07:37:53

对一个文本文件中的整数进行处理,统计出有多少对相同整数,并计算出它们之间在数组中的位置,并把位置的间隔从大至小排序。

#!/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";


# cat data_file
5 7 3 1 1
1 7 1 2 3
2 0 4 9 6
2 8 1 1 3

脚本运行后的输出:

The array is :
5 7 3 1 1 1 7 1 2 3 2 0 4 9 6 2 8 1 1 3

6 pairs found:
(7,7) (3,3) (1,1) (1,1) (2,2) (1,1)

The indices are:
[2,7] [3,10] [4,5] [6,8] [9,11] [18,19]

Sort the indices by range:
[3,10] [2,7] [9,11] [6,8] [18,19] [4,5]

Print a diagram:

    * * * * * * * *                                
  * * * * * *                                    
                * * *                        
          * * *                              
                                  * *        
      * *                                    
5 7 3 1 1 1 7 1 2 3 2 0 4 9 6 2 8 1 1 3
阅读(1405) | 评论(0) | 转发(0) |
0

上一篇:[C程序] 链表

下一篇:[Perl脚本] 作品2号

给主人留下些什么吧!~~