Break a string containing a polynomial

Posted on

Question :

I created a class with two properties as in the example below:

class Polinomio {
    private int coeficientes;
    private int expoente;

I will create a list to receive a polynomial type where I will receive
the terms to perform the addition, subtraction, and multiplication operations.

List<Polinomio> lst = new ArrayList<Polinomio>();

When I pass a string as any of these below in the constructor would like to break the terms, but I’m not getting it.

  • a) -4x ^ 5 + 3x ^ 2 + 4
  • b) -4x ^ 3 + 3x ^ 2-8
  • c) 3x ^ 3 – 3x ^ 2 + 4
  • d) 3x ^ 3 – 3x ^ 2 + 2

When it crashes it would be.

  • a) lst = p1 (-4.5), p2 (3.2), p3 (4.0)
  • b) lst = p1 (-4.3), p2 (3.2), p3 (-8.0)
  • c) lst = p1 (3.3), p2 (-3.2), p3 (4.0)
  • d) lst = p1 (3.3), p2 (-3.2), p4 (4.0)

p1, p2, p3 .. are the positions that the elements will be in the list.
In case of the last term when it is only 1 number without “x” it writes as zero. By default the polynomials will have this same variable “x”.

How can I break terms?


Answer :

You can use Pattern : some thing of type Pattern.compile("(?=[+-])").split(…) will return a list of monomials (bits type -2x^3 , +3x^4 , 7 ); you can use similar ideas (break in ^ and x ) to separate coefficients and exponents.

You have to pay attention to the fact that you do not usually write many terms of a polynomial (eg -x^3+x^2 , where coefficients are all implicit), and you can find a “ghost” monomial at the beginning of the list that Pattern will return, when the polynomial starts with a minus sign.

(On the Pattern page you have an explanation of how regular expressions work – the .compile() parameter – but what you need to know to understand how this idea works is that eg Pattern.compile("(?=[aeiou])").split("abacaxi") will return the {"ab", "ac", "ax", "i"} list % – in general, the .split() parameter will be broken immediately before the characters you placed in brackets in .compile() .)


It worked!
code that I made as an example now I can walk from here, thank you!

public static void main(String[] args){

    String poli = "-3x^3 - 3x^2 + 4";

    Pattern pegapoli = Pattern.compile("(?=[+-])");    
    String[] m = pegapoli.split(poli);




Leave a Reply

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