Reputation: 23
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
Reputation: 10184
+-
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. entry
. 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