package funpoly.visitor; import funpoly.*; /** * Adds host polynomial to input polynomial. Returns the resulting sum polynomial. * @author Dung X. Nguyen */ public class AddAlgo implements IVisitor { public final static AddAlgo Singleton = new AddAlgo (); private AddAlgo() { } /** * @param poly a Constant polynomial * @param input a APolynomial * @return a APolynomial representing the sum of poly and input. */ public Object forConst(APolynomial poly, Object input) { APolynomial p = (APolynomial)input; int pDegree = p.getDegree(); return 0 == pDegree? PolyFactory.MakeConstPoly(poly.getLeadCoef() + p.getLeadCoef()): p.execute(this, poly); // also: forNonConst (p, poly); } /** * @param poly a non-constant APolynomial * @param input a APolynomial * @return a APolynomial representing the sum of poly and input. */ public Object forNonConst(APolynomial poly, Object input) { APolynomial p = (APolynomial)input; int pCoef = p.getLeadCoef(); int pDegree = p.getDegree(); int polyCoef = poly.getLeadCoef(); int polyDegree = poly.getDegree(); return (pDegree < polyDegree)? PolyFactory.MakePoly (polyCoef, polyDegree, (APolynomial)poly.getLowerPoly().execute (this, p)): (pDegree == polyDegree)? PolyFactory.MakePoly (polyCoef + pCoef, polyDegree, (APolynomial)poly.getLowerPoly().execute(this, p.getLowerPoly())): PolyFactory.MakePoly (pCoef, pDegree, (APolynomial)poly.execute(this, p.getLowerPoly())); } }