package av2010;

/**
 * 
 * @author lombardy
 *
 * Exercice 2
 */

public class Polynome implements Fonction {
	private double[] coefficients;
	private String var="X";
	
	public Polynome(double[] coefficients){
		this.coefficients = new double[coefficients.length];
		for (int i = 0; i < coefficients.length; i++) {
			this.coefficients[i] = coefficients[i];
		}
	}

	public int degre(){
		for(int i=coefficients.length-1; i>0; i--)
			if(coefficients[i] != 0)
				return i;
		return 0;
	}

	public double getCoeff(int i){
		if(i >= coefficients.length)
			return 0.;
		return coefficients[i];
	}
	
	public void setCoeff(int i, double c){
		if(i >= coefficients.length){
			double[] tmp= new double[i+1];
			for (int j = 0; j < coefficients.length; j++)
				tmp[j] = coefficients[j];
			coefficients = tmp;	
		}
		coefficients[i] = c;	
	}
	
	@Override
	public String toString(){
		boolean suite=false;
		StringBuffer res = new StringBuffer();
		for(int i=0; i<=degre(); i++){
			double c = coefficients[i];
			if(c==0)
				continue;
			if(suite && c>0)
				res.append('+');
			if(!suite)
				suite=true;
			if(i==0 || c*c!=1)
				res.append(c);
			else if(c==-1)
				res.append('-');
			if(i>0)
				res.append(var);
			if(i>1)
				res.append('^').append(i);
		}
		return res.toString();
	}
	
	@Override
	public Fonction derivee() {
		double[] coefDer = new double[degre()];
		for (int i = 0; i < coefDer.length; i++)
			coefDer[i] = (i+1)*coefficients[i+1];
		return new Polynome(coefDer);
	}

	@Override
	public double evalue(double x) {
		double r=0;
		for(int i=coefficients.length-1; i>=0; i--){
			r *= x;
			r += coefficients[i];
		}
		return r;
	}

	@Override
	public void setNomVariable(String var) {
		this.var = var;
	}

}
