Transform an array into a polynomial (Fairly new to java)

What this method should do is take an array of doubles and convert them into a polynomial, for example, if the array is given was [2.0, 3.0, -2.0] the method’s output would be 2.0x^2 + 3.0x^1 – 2.0. What I have done is created two loops however, when I do this both outputs are separated as expected. My output looks like this 2.0 1.0 2.0 1.0 x^3 x^2 x^1, if there is a way to have the exponents printed after the coefficient that would solve this issue.

public String printPoly(Double[] doubles) {

    String polynomialString = "";

    for (int i = 0; i < doubles.length; i++) {
        polynomialString += doubles[i] + " ";
    }

    for (int j = doubles.length-1; j >= 0; j--) {
        if (j == 0) {
            polynomialString += " ";
            break;
        }
        polynomialString += "x^" + j + " ";
    }
    return polynomialString;
}

}

Answer

You can build the resultString using one for-loop. Initialize a counter variable which you count backwards which is representing your ^3 part. This variable starts at your array.length-1 end runs down to zero in the iterations this is how you can create

4.0 x^3
2.0 x^2
0.5 x^1
2.0 x^0

It runs basically backwards so you should decrement it in each iteration

int backCounter = doubles.length-1;

inside your one for-loop do

polynomialString += doubles[j] + "x^" + backCounter + " ";

backCounter--;

Here is a working solution

package so;

import java.util.*;

public class RemoveString {

    public static void main(String[] args) {
        Double[] someNumbers = { 2.0, 3.0, 1.0, 0.5 };
        String s = RemoveString.printPoly(someNumbers);
        System.out.println(s);
    }

    public static String printPoly(Double[] doubles) {

        String polynomialString = "";
        int backwardsCounter = doubles.length - 1;

        for (int i = 0; i < doubles.length; i++) {
            polynomialString += doubles[i] + "x^" + backwardsCounter + " ";
            backwardsCounter --;
        }

        return polynomialString;
    }
}

Produces the output

2.0x^3 3.0x^2 1.0x^1 0.5x^0 

Leave a Reply

Your email address will not be published. Required fields are marked *