Decomposing Polynomial String in Java

1.1k Views Asked by At

I want to process this polynomial

String str = "2*x^2 + x + 2*x^2 + 8 - x^3";

I have split the string with plus and minus operator and got the 2*x^2. I am finding it difficult to work out this operation.

I know first i will need to work out value of x lets say x=2, just don't know how can I parse string to integer as there are other parts of the string to be parsed as well.

do i need to decompose "2*x^2" too?

How do I find * in string. I know i can use str.contains("*"), for this purticular operation i know whats coming after 2*x^2 but if user enters the polynomial thats the tricky bit.

Output is so far Operation 2*x^2 + x + 2*x^2 + 8 - x^3
Plus Splits
0 2*x^2
1 x
2 2*x^2
3 8 - x^3
Minus Splits
0 2*x^2 + x + 2*x^2 + 8
1 x^3

2

There are 2 best solutions below

0
On

Try to use this: http://projects.congrace.de/exp4j/

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
        .variables("x", "y")
        .build()
        .setVariable("x", 2.3)
        .setVariable("y", 3.14);
double result = e.evaluate();
3
On

In general this operation called "parse an expression" and covered in many books, articles and questions on so like How to parse a mathematical expression given as a string and return a number?.

In this particular case it looks like format is very limited and you can get by with manually splitting string and constructing corresponding data structure:

  1. split by plus and minus first similar to what you already do (How to split a string, but also keep the delimiters?)
  2. in resulting groups split by * if present.
  3. if got 3 groups (number, *, power) - split last by ^.

If you can't use regular expression to split strings - use indexOf to find particular characters (like * in your question - s.indexOf('*') ) and use substring to cut out parts of the string.

As part of building AST for that expression you'll need to How to convert a String to an int in Java? too.