package com.company;
/*
Рекурсия для мат. выражения
*/
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
Рекурсия для мат. выражения
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
solution.recurse("2*-7", 0); //expected output 0.5 6
solution.recurse("-7", 0); //expected output 0.5 6
solution.recurse("sin(2*((-5+1.5)*4)+28)", 0); //expected output 0.5 6
solution.recurse("sin(2*(-5+1.5*4)+28)", 0); //expected output 0.5 6
solution.recurse("tan(2025 ^ 0.5)", 0); //expected output 0.5 6
solution.recurse("1.563", 0); //expected output 0.5 6
solution.recurse("-0", 0); //expected output 0.5 6
solution.recurse("-1 * 0", 0); //expected output 0.5 6
}
public void recurse(final String expression, int countOperation) {
try {
double result = Double.parseDouble(expression);
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(result) + " " + countOperation);
} catch (NumberFormatException e) {
Pattern pattern = Pattern.compile("[(][^(]+?[)]");
Matcher matcher = pattern.matcher(expression);
String founded = "";
while (matcher.find()) {
founded = matcher.group();
}
if (founded.equals("")) {
founded = expression;
}
String firstMathOperation = founded.replaceAll("[\\s()]", "").replace("-", "+-1*");
double sumResult = 0;
String[] terms = firstMathOperation.split("\\+");
countOperation += terms.length - 1;
for (int i = 0; i < terms.length; i++) {
if (!terms[i].equals("")) {
if (terms[i].endsWith("*") || terms[i].endsWith("/") || terms[i].endsWith("^")) {
terms[i + 1] = terms[i] + terms[i + 1];
i++;
}
String[] multiples = terms[i].split("\\*");
countOperation += multiples.length - 1;
double multiplicationResult = 1;
for (String multiple : multiples) {
String[] divides = multiple.split("/");
countOperation += divides.length - 1;
double divisionResult = 0;
for (int k = 0; k < divides.length; k++) {
String[] degrees = divides[k].split("\\^");
countOperation += degrees.length - 1;
double exponentiationResult = 1;
for (int j = degrees.length - 1; j >= 0; j--) {
double value;
try {
value = Double.parseDouble(degrees[j]);
} catch (NumberFormatException exception) {
double radians;
if (degrees[j].startsWith("sin")) {
radians = Double.parseDouble(degrees[j].replace("sin", "")) / 180 * Math.PI;
value = Math.sin(radians);
} else if (degrees[j].startsWith("cos")) {
radians = Double.parseDouble(degrees[j].replace("cos", "")) / 180 * Math.PI;
value = Math.cos(radians);
} else if (degrees[j].startsWith("tan")) {
radians = Double.parseDouble(degrees[j].replace("tan", "")) / 180 * Math.PI;
value = Math.tan(radians);
} else {
throw new RuntimeException("Unacceptable expression!");
}
countOperation++;
}
if (j == degrees.length - 1) {
exponentiationResult = value;
} else {
exponentiationResult = Math.pow(value, exponentiationResult);
}
}
if (k == 0) {
divisionResult = exponentiationResult;
} else {
divisionResult /= exponentiationResult;
}
}
if (divisionResult < 0) {
countOperation--;
}
multiplicationResult *= divisionResult;
}
sumResult += multiplicationResult;
}
}
recurse(expression.replace(founded, sumResult + ""), countOperation);
}
//implement
}
public Solution() {
//don't delete
}
}
Виталий
36 уровень
Подскажите пожалуйста, что делаю не так?
Решен
Комментарии (1)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Павел Безумный учёный Expert
1 марта 2021, 10:42полезный
Протестируйте алгоритм на таких выражениях:
Обратите внимание, что при выводе в консоль результата вычислений в качестве десятичного разделителя должна использоваться точка.
+1