Reputation: 3
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 (e.g 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..
Upvotes: 0
Views: 1717
Reputation: 45
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]
Upvotes: 2
Reputation: 3672
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.
Upvotes: 0