Polynomial String Not Split

1.6k Views Asked by At

I have 2 Strings.

String s1 = "x^5 + 22.6x^4 - x^3 - 41.3x^1 + 4.2";
String s2 = "-x^3  -  3x^2 + 2x + 22";

I want to split the strings. I should find coefficients and exponents. I used replace method like this: s1.replaceAll("//s+",""); So I remove all whitespace. When I use split method.

String array[] = s2.split("//+");

My outputs are :

-x^3-3x^2
+2x
+22

But it is not answer. Using one split method, I will divide all the parts.

But I want to split the strings when special code "+" and "-" together. But I didn't again. Without removing whitespaces, can I split my Strings?

2

There are 2 best solutions below

0
On

Splitting that string isn't that complicated. But you need some knowledge about regular expressions.

I'll give you first a code snippet:

String poly = "x^5 + 22.6x^4 - x^3 - 41.3x + 4.2";
String[] terms = poly.replace(" ", "").split("(?=\\+|\\-)");
System.out.println(Arrays.toString(terms));

Map<Integer, Double> analyzed = new HashMap<>();
for (String term : terms)
{
    String[] splitAroundX = term.split("x", 2);
    int exponent = 0;
    if (splitAroundX.length > 1)
    {
        String sExp = splitAroundX[1].replace("^", "");
        exponent = sExp.isEmpty() ? 1 : Integer.parseInt(sExp);
    }
    String sCoeff = splitAroundX[0];
    double coefficient =
        sCoeff.isEmpty() ? 1.0 : ("-".equals(sCoeff) ? -1.0 : Double.parseDouble(sCoeff));
    analyzed.put(Integer.valueOf(exponent), Double.valueOf(coefficient));
}
System.out.println(analyzed);

Note that this only works with syntactically correct polynomials.

There are some parsing pitfalls there. For example, you have to take care of empty strings, which represent the value "1" some times.

The main problem - however - is to get the regular expressions right.

The first one is the expression (?=\\+|\\-). This uses an alternation group because you want to match either on "+" or on "-". Additionally, you want to keep the operator sign while splitting as it also is the sign for the coefficient. For this you have to use a positive lookahead (the "?=" part).

Read more on regular expressions on http://www.regular-expressions.info/.

The second one is the splitting around "x" but with a fixed limit of 2. That allows the split function to also split the term "-41.3x" into the array {"-41.3", ""}. Without the limit, it would only be a 1-lengthed array, and that would be ambiguous with no "x" at all.

And of course I initially removed all whitespaces as this simply makes parsing a lot easier.

The two output statements above produce the following results:

[x^5, +22.6x^4, -x^3, -41.3x, +4.2]

{0=4.2, 1=-41.3, 3=-1.0, 4=22.6, 5=1.0}

0
On

One way is to iterate throught all the substrings of your polinome that contains no whitespace ( basically all variable and operator itself. Then you can decide if you see an operator or something else in your current iteration and handle them separately. If you don't look at an operator, you can just split your current match by the character ^, and the 0th find is your coeff, and the 1th is your exponent.

    Pattern pattern = Pattern.compile("([^ ]+)");
    Matcher matcher = pattern.matcher("x^5 + 22.6x^4 - x^3 - 41.3x^1 + 4.2");

    while (matcher.find()) {
        String match = matcher.group(1);
        if (Arrays.asList("+", "-").contains(match)) {
            // something you do with operators
        }

        if (match.matches(".*\\^.*")) {
            // your match is 'x^y' format
            String[] split = match.split("\\^");
            String coefficient = split[0]; // your coefficient
            String exponent = split[1]; // your exponent

            System.out.println(coefficient + " ^ "+exponent); // see your result

        } else {
            // something you do when the current variable doesn't have an exponent
        }
    }