Kont Mosyo
Kont Mosyo

Reputation: 23

How to split a mathematical equation into coefficients and exponents?

I am computing some equations in java. I want to use single linked list. Nodes should have two integer data: coefficient and exponent.

Here an example: equation = 18x^75-4x^56+18x^37+18x^19-18x^9-12

linked list= node1(18, 75)->node2(-4, 56)... it should be like that.

I am asking just splitting.

String equation = "18x^75-4x^56+18x^37+18x^19-18x^9-12";
String[] terms = equation.split("[0-9]+(?<=[-+*/()])|(?=[-+*/()])");
for (String term : terms) {
     System.out.println(term);
}

Upvotes: 0

Views: 398

Answers (1)

VHS
VHS

Reputation: 10184

  • You can first split your equation with +- delimiter so that you get an array of each individual term. Note that you will want to retain the sign if the term is negative.
  • Then you can stream through the array of terms and for each term, split it further with the delimiter "x^". With this you will get two split items - one to the left of x^ is your coefficient and to the right is the exponent.
  • Store the coefficient and exponent in an entry.
  • Store the entry in your linked list.

Here's a working sample:

String equation = "18x^75-4x^56+18x^37+18x^19-18x^9-12";
String[] terms = equation.split("\\+|(?=\\-)");
Arrays.stream(terms).forEach(System.out::println);
List list = new LinkedList<Map.Entry<Integer, Integer>>();
Arrays.stream(terms).filter(t -> t.contains("x^")).forEach(
        s -> list.add(new AbstractMap.SimpleEntry(Integer.parseInt(s.split("x\\^")[0]), Integer.parseInt(s.split("x\\^")[1]))));
//Finally, add the constant term.
list.add(new AbstractMap.SimpleEntry(Integer.parseInt(terms[terms.length - 1]), 0));

Upvotes: 2

Related Questions