从9x9矩阵中抽取中间菱形区域打印 - perl
起因: 源自于c的练习题,打印diamond,因为perl不需编译,方便调试,故先用perl实现一下
关键: 没有想到好的思路,只能借助于上一篇打印上下三角矩阵的方法,把菱形拆成上下左右4个三角矩阵区域来实现。
1 #!/usr/bin/perl -w 2 use strict; 3 ## ------------------------------- diamond ----------------------------------------- 4 ## upper peak 5 for my $row (reverse(1..9)) 6 { 7 ## upper left 8 for my $col(1..9) 9 { 10 if($col >= $row) 11 { 12 print "* "; 13 } 14 else 15 { 16 print " "; 17 } 18 } 19 20 ## upper right 21 for my $col(reverse(1..9)) 22 { 23 if($col > $row) 24 { 25 print "* "; 26 } 27 else 28 { 29 print " "; 30 } 31 } 32 print "\n"; 33 } 34 35 ## lower peak 36 for my $row (2..9) 37 { 38 print " "; 39 ## lower left 40 for my $col(2..9) 41 { 42 if($col >= $row) 43 { 44 print "* "; 45 } 46 else 47 { 48 print " "; 49 } 50 } 51 52 ## lower right 53 for my $col(reverse(2..9)) 54 { 55 if($col > $row) 56 { 57 print "* "; 58 } 59 else 60 { 61 print " "; 62 } 63 } 64 print "\n"; 65 }
输出: