Currently I am writing a compareTo method for quadratic functions in the form: ax^2 + bx + c.
a, b, c are integer coefficients that are passed to the class through the constructor.
In the compareTo method, I am supposed to first compare the a-coefficients between two functions, but if they are equal, I compare the b-coefficients. If the b's are equal, I compare the c's.
The method that I came up for this ended up being pretty ugly:
public int compareTo(QuadraticFunction other)
{
if (a > other.a)
return 1;
else if (a < other.a)
return -1;
else if (b > other.b)
return 1;
else if (b < other.b)
return -1;
else if (c > other.c)
return 1;
else if (c < other.c)
return -1;
else
return 0;
}
So I was wondering, if you have these "tiered" systems of comparisons (like compare a's before b's before c's), what's the best way to implement them? I can't imagine writing a method like mine if you have to go through 10+ variables.
For an arbitrary number of coefficients (all of the same type), you should store them in a List
(or something similar), rather than individually-named member variables. That allows you to convert your example code into an iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With