Breaking a string containing a polynomial

Asked

Viewed 345 times

3

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 for performing the sum, subtraction and multiplication operations.

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

When I pass one string like any of these below in the builder would like to break the terms, but I’m not getting.

  • 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 broke 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 the elements will be in the list. In the case of the last term when it is only 1 number without "x" it writes as zero. By default the polynomials will have the same variable "x".

How can I break the terms?

  • Related: "Equation solving" (a little more general, maybe Overkill for your case, but I’m mentioning case you find useful)

2 answers

4


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

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

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

  • A regex to catch a monomial: (-?\d*x\^\d+|-?\d*x|-?\d+)

1

It worked out well! code I made an example of now I can walk from here, thank you!

public static void main(String[] args){

    String poli = "-3x^3 - 3x^2 + 4";
    Pattern.compile("(?=[+-])").split(poli);

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

    System.out.println(m[0]);
    System.out.println(m[1]);
    System.out.println(m[2]);

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.