In: Computer Science
Task 3: Class Polynomial (Version 2)
In a separate namespace, the class Polynomial (Version 2) re-implements a polynomial as a linear array of terms ordered by exponent. Each polynomial is also reduced to simplest terms, that is, only one term for a given exponent.
public class Polynomial
{
// P is a linear array of Terms
private Term[ ] P;
…
// Re-implement the six methods of Polynomial (including the constructor)
…
}
public class Polynomial {
// The coefficients of the polynomial.
// Array index i stores the degree i coefficient.
// For example, z^2 + 2z + 3 is stored is {3, 2, 1}.
private final Term[] coeffs;
public Polynomial(Term[] coeffs) {
// Why copy the array? Well, if we don't make a copy, the person
// who gave us the array could change the values later (which
// could be confusing).
this.coeffs = new Term[coeffs.length];
for (int i = 0; i < coeffs.length; i++) {
this.coeffs[i] = coeffs[i];
}
}
public Polynomial() {
this(new Term[0]);
}
// This is a static factory method, although it could technically be
// made a constructor. My personal preference is to have only one "real"
// constructor that does all the initialization work, plus maybe a few
// "simplified" constructors that delegate to it using `this(...)` and
// pass in default arguments (in this file, the no-argument constructor
// is an example of a "simplified" constructor). I consider this method
// different enough to warrant a named factory method.
public static Polynomial linear(Term a, Term b) {
return new Polynomial(new Term[]{b, a});
}
// Technically incorrect: a polynomial like 0z^2 + z + 1 should have
// degree 1 (the highest non-zero term is the degree-1 term), but this
// will report degree 2. How could you fix that?
public int degree() {
return coeffs.length - 1;
}
// Why use a getter here?
public Term getCoeff(int i) {
return coeffs[i]; // may throw IndexOutOfBoundsException
}
// Like Term, this class is immutable so we return a new instance.
public Polynomial add(Polynomial other) {
int newDeg = Math.max(degree(), other.degree());
Term[] newCoeffs = new Term[newDeg + 1];
for (int i = 0; i < newCoeffs.length; i++) {
newCoeffs[i] = getCoeff(i).add(other.getCoeff(i));
}
return new Polynomial(newCoeffs);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int exp = 0; exp < coeffs.length; exp++) {
if (exp > 0) {
sb.append(" + ");
}
sb.append("(");
sb.append(coeffs[exp].toString());
sb.append(")z^");
sb.append(Integer.toString(exp));
}
return sb.toString();
}
}