[英]How to split a mathematical equation into coefficients and exponents?
我正在用Java計算一些方程式。 我想使用單個鏈表。 節點應具有兩個整數數據:系數和指數。
這里是一個示例:公式= 18x ^ 75-4x ^ 56 + 18x ^ 37 + 18x ^ 19-18x ^ 9-12
鏈表= node1(18,75)-> node2(-4,56)...應該是這樣的。
我要分裂。
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);
}
+-
分隔符來拆分方程式,以便獲得每個單獨項的數組。 請注意,如果該術語為負數,則您將希望保留該符號。 entry
。 這是一個工作示例:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.