简体   繁体   中英

How do I get the coefficients and exponents from a polynomial string?

I am trying to extract coefficients and exponents from a Polynomial string and then storing them to an array so that I could use those arrays to create a new term to which I can do math operations on (eg add, subtract, and multiply)

List<Term> poly = new ArrayList<>;
String poly = "26x^7+5x^6-8x^3-2";

int[] coeff = // Something like using split method here to get coeffs
int[] expo = // Same here but with exponents

for(int i = 0; i < coeffs.length; i++){
    poly.add(new Term(coeff[i], expo[i]);
}

Problem is, I really don't know how to do it. I've tried so many ways and it all led to an error..

Here is a solution that ignores the extra complications with x^1 and x^0 and coefficient=1.

It uses Lookahead in the regex as described here

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    public static void main(String[] args) {
        // expect format ax^n for each term. in particular in the cases a=1, x=1 and x=0.
        String poly = "26x^7+5x^6-8x^3+1x^1-2x^0";

        // remove ^ and then split by x and by + and - keeping the sign
        String[] numbers = poly.replace("^", "").split("((?=\\+)|(?=\\-)|x)");

        List<Integer> coeff = new ArrayList<>();
        List<Integer> expo = new ArrayList<>();

        // we can now assume that for every coefficient there is an exponent
        for (int i = 0; i < numbers.length; i += 2) {
            coeff.add(Integer.parseInt(numbers[i]));
            expo.add(Integer.parseInt(numbers[i + 1]));
        }

        System.out.println(coeff);
        System.out.println(expo);
    }
}

Output:

[26, 5, -8, 1, -2]
[7, 6, 3, 1, 0]

I would try splitting the poly string using the "+" or "-" chars. If there is a regex split method in java, that would be suitable.

The array resulting from this split is what should be iterated over in your loop in order to populate the poly List.

Another thing to be mindful of is the "-2" term in your polynomial, which is technically x^0 and any "ax" terms, which are x^1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM