THINK FIRST·CODE LATER

← All labs

A generic matrix: one algorithm, two number types

Problem

Matrix addition and multiplication are the same algorithms whether the elements are integers or exact fractions; only "add two elements" and "multiply two elements" differ. Write:

  • an abstract class GenericMatrix<E> with the abstract methods add(E, E), multiply(E, E) and zero(), and the concrete methods addMatrix(E[][] a, E[][] b) and multiplyMatrix(E[][] a, E[][] b), written once;
  • IntegerMatrix extends GenericMatrix<Integer>;
  • a small immutable class Fraction (always in lowest terms) and FractionMatrix extends GenericMatrix<Fraction>.

The input gives the type (int or frac), the size n, then the n × n matrices A and B; fractions are written 3/4 (or 2). Print A + B and A × B, each element in a field of width 8. For the input

int
2
1 2
3 4
5 6
7 8

the program prints

A + B
       6       8
      10      12
A x B
      19      22
      43      50

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d2-9-data-1.txt

int
2
1 2
3 4
5 6
7 8
What your program must print for d2-9-data-1.txt
A + B
       6       8
      10      12
A x B
      19      22
      43      50

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d2-9-data-1.txt

Windows PowerShell does not understand <:

Get-Content d2-9-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.