package arrayPoly.visitor; import arrayPoly.*; /** * Adds host polynomial to input polynomial. Returns the resulting sum polynomial.
 * Copyright 2000, by Dung X. Nguyen, All rights reserved.
 
* @author Dung X. Nguyen * @since 02/16/2000 */ public class AddAlgo implements IVisitor { public final static AddAlgo Singleton = new AddAlgo (); private AddAlgo() { } /** * Uses a helper visitor to add a constant to the input APolynomial. * The helper visitor can be implemented as an anonymous inner class. * @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; return p.execute (AddConst.Singleton, new Double (poly.getLeadCoef())); /* //Instead of defining explicitly the helper visitor AddConst, we can uses anonymous //inner class to add a constant. The code is a little harder to read. return p.execute ( new IVisitor () { public Object forConst (APolynomial poly, Object input) { return PolyFactory.MakeConstPoly (poly.getLeadCoef() + ((Double)input).doubleValue ()); } public Object forNonConst(APolynomial poly, Object input) { APolynomial lowerSum = (APolynomial)poly.getLowerPoly().execute (this, input); return PolyFactory.MakePoly (poly.getLeadCoef(), poly.getDegree(), lowerSum); } }, new Double (poly.getLeadCoef())); */ } /** * @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; double pCoef = p.getLeadCoef(); int pDegree = p.getDegree(); double 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())); } }