Given a polynomial, for example, 5x^4 - 1x^2 +2x^2 -3 +5x I create the following three arrays whose indexes match up with the variable,degree, and coefficient that each "item" in the polynomial has.
coefficentArray=[5, -3, 2, -1, 5]
variableArray = [x, , x, x, x]
degreeArray = [1, 1, 2, 2, 4] //sorted on
I am attempting to write code that adds up all of the "items" with the same degrees and same variable, and returns a String of the new polynomial, so for instance what I'm looking for here would be +5x^4 +1x^2 +5x^1 -3x^0. Here is my function so far...
public static String putItTogether(int[] array,int[] array1, String[] array2, int count)
{
int j = count; //count is number of items in arrays
StringBuilder builder = new StringBuilder();
for (int i=count; i<=0 ; i--) {
int answer = 0;
while (array[j] == array[j-1]) { //array = degrees //array1 = coefficients // array2 = variable
if (array2[j] == array2[j-1]) { //if they both have x in same index
answer = array1[j] + array1[j-1];//add the coefficients
}
j--;
}
String coefficientString = Integer.toString(answer); //create string from answer
String degreeString = Integer.toString(array[j]); //get the degree and turn it into a String
if (answer < 0)
builder.append("-") //if answer negative, add negative sign
else
builder.append("+") // else add positive sign
builder.append(coefficientString); //add coefficient to builder
builder.append("x"); //add "x" to coefficient in builder
builder.append("^"); //add the "^" after the "x"
builder.append(degreeString); //finally add the degree after the "^"
buider.append(" "); //add space inbetween
}
}
return builder.toString();
}
Using the polynomial given at the top as input, I'm receiving +0x^0 +0x^0.Been staring at it for a couple hours now and can't seem to find anything, so thought I'd try to get another set of eyes on it. Thanks for your time, it's truly appreciated. Also, if you think I should kill my little "code-baby" and approach the problem from a different angle don't be afraid to tell me!
Aucun commentaire:
Enregistrer un commentaire