Solution Review: Print a Matrix
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
We'll cover the following...
Let’s look at the solution first before jumping into the explanation:
Press + to interact
Perl
sub printMat {$n = @_[0];@arr=();for ($i=0;$i<$n;$i++) {for ($j=0;$j<$n;$j++){if ($i==$j){ # if row=column=> fill the matrix with 0$arr[$i][$j] = 0;}elsif($i>$j){ # if row>columns=> fill matrix with -1$arr[$i][$j] = -1;}else { # if row<columns=> fill matrix with 1$arr[$i][$j] = 1;}}}for ($i=0;$i<$n;$i++) {for ($j=0;$j<$n;$j++){sub printMat {$n = @_[0];@arr=();for ($i=0;$i<$n;$i++) {for ($j=0;$j<$n;$j++){if ($i==$j){ # if row=column=> fill the matrix with 0$arr[$i][$j] = 0;}elsif($i>$j){ # if row>columns=> fill matrix with -1$arr[$i][$j] = -1;}else { # if row<columns=> fill matrix with 1$arr[$i][$j] = 1;}}}for ($i=0;$i<$n;$i++) {for ($j=0;$j<$n;$j++) {print $arr[$i][$j]." ";}print "\n";}} }print "\n";}}printMat(4);
Explanation
We want to create a matrix (two-dimensional array) of size passed from the printMat
subroutine. @_[0]
is used to get the size as this is the only argument passed to this subroutine. The elements in the array are stored using the following conditions:
- if
$i
is equal to$j
then store 0, handling diagonal - else if
$i
is greater than$j
then store -1, handling all elements below diagonal - else store 1, handling all elements above diagonals
We use a nested for
loop to print all elements of the array.