File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed
Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,16 @@ public static Polynomial parse(String s) {
1818 return new Polynomial (Parser .parse (s ));
1919 }
2020
21+ public Polynomial add (String s ) {
22+ List <Fraction > other = Parser .parse (s );
23+ int rank = Math .max (coefficients .size (), other .size ());
24+ List <Fraction > r = new ArrayList <>(rank );
25+ for (int i = 0 ; i < rank ; i ++) {
26+ r .add (get (i ).add (i < other .size () ? other .get (i ) : Fraction .ZERO ));
27+ }
28+ return new Polynomial (r );
29+ }
30+
2131 @ Override
2232 public String toString () {
2333 List <String > result = new ArrayList <>(coefficients .size ());
@@ -41,4 +51,24 @@ public String toString() {
4151 }
4252 return String .join (" " , result );
4353 }
54+
55+ @ Override
56+ public boolean equals (Object o ) {
57+ if (this == o ) return true ;
58+ if (o == null ) return false ;
59+ if (!(o instanceof Polynomial )) return false ;
60+ return coefficients .equals (((Polynomial ) o ).coefficients );
61+ }
62+
63+ @ Override
64+ public int hashCode () {
65+ return coefficients .hashCode ();
66+ }
67+
68+ private Fraction get (int i ) {
69+ if (i >= coefficients .size ()) {
70+ return Fraction .ZERO ;
71+ }
72+ return coefficients .get (i );
73+ }
4474}
Original file line number Diff line number Diff line change 77class PolynomialTest {
88
99 @ Test
10- void parse () {
10+ void polynomialToString () {
1111 assertEquals ("x^5 - x - 1" , Polynomial .parse ("-x + x^5 - 1" ).toString ());
1212 }
13+
14+ @ Test
15+ void add () {
16+ assertEquals (Polynomial .parse ("2x + 3" ), Polynomial .parse ("x + 1" ).add ("x + 2" ));
17+ }
18+
19+ @ Test
20+ void polynomialEquals () {
21+ assertEquals (Polynomial .parse ("x^5 - x - 1" ), Polynomial .parse ("-x + x^5 - 1" ));
22+ }
1323}
You can’t perform that action at this time.
0 commit comments