#!/usr/bin/perl
#
# matrix.pl
# Create two random matrices and multiply them
# Lets the user input rows and colums of A, B.
# Does not let user input Rows of matrix B, because this should be
#  the same as the number of columns of matrix A (otherwise the
#  matrices could not be multiplied.
#

print "Enter number of rows in matrix A: "; $An = <STDIN>; chomp($An);
print "Enter number of cols in matrix A: "; $Am = <STDIN>; chomp($Am);
$Bn = $Am;
print "Enter number of rows in matrix B: $Bn\n";
print "Enter number of cols in matrix B: "; $Bm = <STDIN>; chomp($Bm);
$Cn = $An; $Cm = $Bm;			# Dimensions of C from A and B

print "\nAB will yield a $Cn x $Cm matrix\n";

for($i = 0; $i < $An; $i++) {
  for($j = 0; $j < $Am; $j++) {
    $A[$i][$j] = int(rand(11)) - 5;
  }
}

for ($i = 0; $i < $Bn; $i++) {
  for($j = 0; $j < $Bm; $j++) {
    $B[$i][$j] = int(rand(11)) - 5;
  }
}

for($i = 0; $i < $Cn; $i++) {
  for($j = 0; $j < $Cm; $j++) {
    for($k = 0; $k < $Am; $k++) {
      $C[$i][$j] += ($A[$i][$k]) * ($B[$k][$j]);
    }
  }
}

print "\nMatrix A:\n";
for($i = 0; $i < $An; $i++) {
  print "| ";
  for($j = 0; $j < $Am; $j++) {
    if($A[$i][$j] < 0) {
      print "$A[$i][$j] ";
    } else {
      print " $A[$i][$j] ";
    }
  }
  print "|\n";
}

print "\nMatrix B:\n";
for($i = 0; $i < $Bn; $i++) {
  print "| ";
  for($j = 0; $j < $Bm; $j++) {
    if($B[$i][$j] < 0) {
      print "$B[$i][$j] ";
    } else {
      print " $B[$i][$j] ";
    }
  }
  print "|\n";
}

print "\nMatrix C:\n";
for($i = 0; $i < $Cn; $i++) {
  print "| ";
  for($j = 0; $j < $Cm; $j++) {
    if($C[$i][$j] < 0) {
      print "$C[$i][$j] ";
    } else {
      print " $C[$i][$j] ";
    }
  }
  print "|\n";
}
print "\n";
