-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskFour.java
More file actions
108 lines (90 loc) · 3.8 KB
/
taskFour.java
File metadata and controls
108 lines (90 loc) · 3.8 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.util.Stack;
public class taskFour {
static int floorDiv(int a, int b){
if (a * b < 0 && a % b != 0)
return (a / b) -1;
return a/b;
}
// Fungsi untuk mengembalian precedence dari operator
static int precedence(char c) {
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
// Fungsi untuk mengecek jika operator berjalan dari kanan
static boolean isRightAssociative(char c){
return c =='^';
}
public static String infixToPostFix(String s){
Stack<Character> stack = new Stack<>();
StringBuilder resBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// Jika operand ditambahkan pada hasil
if (Character.isLetterOrDigit(c)) {
resBuilder.append(c).append(" ");
}
// Jika '(' di push ke dalam stack
else if (c == '(') {
stack.push('(');
}
// Jika ')' di keluarkan dari dalam stack
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
resBuilder.append(stack.pop()).append(" ");
}
stack.pop();
}
else {
while (!stack.isEmpty() && stack.peek() != '(' &&
(precedence(stack.peek()) > precedence(c) ||
(precedence(stack.peek()) == precedence(c) && !isRightAssociative(c)))){
resBuilder.append(stack.pop()).append(" ");
}
stack.push(c);
}
}
// Keluarkan operator yang sedang berjalan
while (!stack.isEmpty()) {
resBuilder.append(stack.pop()).append(" ");
}
return resBuilder.toString().trim();
}
public static int evaluatePostFix(String exp){
Stack<Integer> stack = new Stack<>();
for(String token : exp.split("\\s+")){
if (token.isEmpty()) continue;
// Jika operand adalah bilangan angka, push ke dalam stack
if (Character.isDigit(token.charAt(0)) || (token.length() > 1 && token.charAt(0) == '-')) {
stack.push(Integer.parseInt(token));
}
else {
int val1 = stack.pop();
int val2 = stack.pop();
switch (token) {
case "+": stack.push(val2 + val1); break;
case "-": stack.push(val2 - val1); break;
case "*": stack.push(val2 * val1); break;
case "/": stack.push(floorDiv(val2, val1)); break;
case "^": stack.push((int) Math.pow(val2, val1)); break;
}
}
}
return stack.pop();
}
public static void main(String[] args) {
String exp = "2*(4+5)/1";
// Step 1: Ubah ke Postfix
String postfix = infixToPostFix(exp);
System.out.println("Infix : " + exp);
System.out.println("Postfix: " + postfix);
// Step 2: Evaluasi hasil Postfix
int result = evaluatePostFix(postfix);
System.out.println("Hasil : " + result);
}
}