aboutsummaryrefslogtreecommitdiff
path: root/Week7/src
diff options
context:
space:
mode:
Diffstat (limited to 'Week7/src')
-rw-r--r--Week7/src/polynomial/Polynomial.java62
-rw-r--r--Week7/src/polynomial/Term.java4
2 files changed, 62 insertions, 4 deletions
diff --git a/Week7/src/polynomial/Polynomial.java b/Week7/src/polynomial/Polynomial.java
index 3b327f4..2a1b28e 100644
--- a/Week7/src/polynomial/Polynomial.java
+++ b/Week7/src/polynomial/Polynomial.java
@@ -1,6 +1,7 @@
package polynomial;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
@@ -61,18 +62,47 @@ public class Polynomial {
*/
@Override
public String toString() {
- return null;
+ StringBuilder sb = new StringBuilder();
+ boolean not_first = false;
+ for (Term t : terms) {
+ if (not_first && t.getCoef() >= 0)
+ sb.append("+");
+ sb.append(t);
+ not_first = true;
+ }
+ return sb.toString();
}
public void plus(Polynomial b) {
+ for (Term t : b.terms)
+ plus(t);
+ }
+
+ public void plus(Term t) {
+ Iterator<Term> iter = terms.iterator();
+ while (iter.hasNext()) {
+ Term this_t = iter.next();
+ if (this_t.getExp() == t.getExp()) {
+ this_t.plus(t);
+ if (this_t.getCoef() == 0)
+ iter.remove();
+ return;
+ }
+ }
+ terms.add(t);
}
-
public void minus(Polynomial b) {
+ b.times(new Polynomial("-1 0"));
+ plus(b);
}
-
public void times(Polynomial b) {
+ Polynomial result = new Polynomial();
+ for (Term that_t : b.terms)
+ for (Term this_t : terms)
+ result.plus(new Polynomial((that_t.getCoef() * this_t.getCoef()) + " " + (that_t.getExp() + this_t.getExp())));
+ terms = result.terms;
}
public void divide(Polynomial b) {
@@ -80,7 +110,31 @@ public class Polynomial {
@Override
public boolean equals(Object other_poly) {
- return false;
+ Polynomial that = (Polynomial) other_poly;
+ if (terms.size() != that.terms.size())
+ return false;
+ for (Term this_t : terms) {
+ Iterator<Term> that_iter = that.terms.iterator();
+ boolean found = false;
+ while (that_iter.hasNext()) {
+ if (this_t.equals(that_iter.next())) {
+ found = true;
+ that_iter.remove();
+ break;
+ }
+ }
+ if (!found) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public double apply(double x) {
+ double result = 0;
+ for (Term t : terms)
+ result += t.apply(x);
+ return result;
}
}
diff --git a/Week7/src/polynomial/Term.java b/Week7/src/polynomial/Term.java
index 67bcf04..b8d9f16 100644
--- a/Week7/src/polynomial/Term.java
+++ b/Week7/src/polynomial/Term.java
@@ -105,6 +105,10 @@ public class Term {
&& coefficient == term.coefficient;
}
}
+
+ public double apply(double x) {
+ return coefficient * Math.pow(x, exponent);
+ }
/**
* A static method for converting scanner input into a term. The expected