-
Notifications
You must be signed in to change notification settings - Fork 34
/
reversed_number_triangles.pl
executable file
·73 lines (61 loc) · 1.7 KB
/
reversed_number_triangles.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 26 July 2015
# Website: https://github.com/trizen
# Generate a set of interesting numeric triangles.
use 5.010;
use strict;
use warnings;
sub triangle {
my ($rows, $type) = @_;
my @triangle = ([1]);
my $n = 1;
foreach my $i (1 .. $rows) {
if ($type == 1) {
foreach my $j (0 .. $#triangle) {
push @{$triangle[$j]}, ++$n;
unshift @{$triangle[$j]}, ++$n;
}
}
elsif ($type == 2) {
foreach my $j (reverse 0 .. $#triangle) {
push @{$triangle[$j]}, ++$n;
unshift @{$triangle[$j]}, ++$n;
}
}
elsif ($type == 3) {
foreach my $j (0 .. $#triangle) {
unshift @{$triangle[$j]}, ++$n;
}
foreach my $j (reverse 0 .. $#triangle) {
push @{$triangle[$j]}, ++$n;
}
}
elsif ($type == 4) {
foreach my $j (reverse 0 .. $#triangle) {
unshift @{$triangle[$j]}, ++$n;
}
foreach my $j (0 .. $#triangle) {
push @{$triangle[$j]}, ++$n;
}
}
else {
die "Invalid type: $type";
}
unshift @triangle, [++$n];
}
return \@triangle;
}
my $width = 4;
my $rows = 8;
foreach my $i (1 .. 4) {
my $triangle = triangle($rows, $i);
foreach my $i (0 .. $#{$triangle}) {
my $row = $triangle->[$i];
print " " x ($width * ($rows - $i));
print map { sprintf "%*d", $width, $_ } @{$row};
print "\n";
}
print "-" x ($width * ($rows + 1) * 2 - $width), "\n";
}