0

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.

variableArray = [x,  , x, x, x]
degreeArray   = [1, 1, 2, 2, 4]  //sorted on
coefficentArray=[5, -3, 2, -1, 5]

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 -3. 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]) { //variable
                    answer = array1[j] + array1[j-1];//coeff
              }
         j--;
         }
      String coefficientString = Integer.toString(answer);
      String degreeString = Integer.toString(count);
      builder.append(coefficientString);
      if (array2[i].equals("x")) {
          builder.append("x");
      }
      if (array[j] != 1) {
         builder.append("^");
         builder.append(degreeString);
      }
    }
    return builder.toString();
}

The call...

String daAnswer = putItTogether(degreeArray, coefficientArray, variableArray, degreeCount);
    System.out.println(daAnswer);

For whatever reason, it's not printing out anything. If you could look over my code, and see where I'm going wrong I'd really appreciate it. Also, any questions about what I'm asking please don't hesitate to ask!

Aaron
  • 49
  • 2
  • 8

0 Answers0