-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmathematical_expression.dart
74 lines (63 loc) · 2.22 KB
/
mathematical_expression.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import 'dart:collection';
double evaluate(String expression) {
// Helper function to evaluate simple expressions without parentheses
double evalSimple(String exp) {
// Use a queue to process operators with the correct precedence
Queue<String> tokens = Queue.from(exp.split(RegExp(r'(\D)')).where((e) => e.isNotEmpty));
Queue<String> operators = Queue.from(exp.split(RegExp(r'(\d+\.?\d*)')).where((e) => e.isNotEmpty));
// Function to perform an operation
double operate(double left, String operator, double right) {
switch (operator) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
default:
throw ArgumentError('Unknown operator: $operator');
}
}
// Stack to handle multiplication and division first
Queue<double> values = Queue<double>();
values.add(double.parse(tokens.removeFirst()));
while (tokens.isNotEmpty) {
String operator = operators.removeFirst();
double value = double.parse(tokens.removeFirst());
if (operator == '*' || operator == '/') {
double prevValue = values.removeLast();
values.add(operate(prevValue, operator, value));
} else {
values.add(value);
operators.addFirst(operator);
}
}
double result = values.removeFirst();
while (operators.isNotEmpty) {
String operator = operators.removeFirst();
double value = values.removeFirst();
result = operate(result, operator, value);
}
return result;
}
// Helper function to handle parentheses
double evalParentheses(String exp) {
while (exp.contains('(')) {
exp = exp.replaceAllMapped(RegExp(r'\(([^()]+)\)'), (match) {
return evalSimple(match.group(1)!).toString();
});
}
return evalSimple(exp);
}
return evalParentheses(expression.replaceAll(' ', ''));
}
void main() {
// Test cases
print(evaluate("1-1")); // Output: 0
print(evaluate("1 -1")); // Output: 0
print(evaluate("1- -1")); // Output: 2
print(evaluate("6 + -(4)")); // Output: 2
print(evaluate("(2 / (2 + 3.33) * 4) - -6")); // Output: 7.2009...
}