简体   繁体   中英

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);
}
  • 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM