106 lines
3.3 KiB
Java
106 lines
3.3 KiB
Java
|
import java.util.ArrayList;
|
||
|
|
||
|
public class Aufgabe1_Kellerautomat {
|
||
|
private static String[] words = {"ZZO", "ZZOZZOO", "ZZZOO", "ZZOO", "ZZOZZO", "ZOZ"};
|
||
|
|
||
|
public static void main(String[] args) {
|
||
|
for (String word : words) {
|
||
|
calculate(word);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static boolean calculate(String word) {
|
||
|
char[] wordChars = word.toCharArray();
|
||
|
ArrayList<Character> stack = new ArrayList<>();
|
||
|
stack.add('$');
|
||
|
|
||
|
int state = 0; //case 0 - 5 = q0 - q5, case -1 = Abfallzustand
|
||
|
|
||
|
for (char symbol : wordChars) {
|
||
|
Character stackSymbol = stack.remove(stack.size() - 1);
|
||
|
switch (state) {
|
||
|
case 0:
|
||
|
if (symbol == 'Z' && stackSymbol == '$') {
|
||
|
stack.add('$');
|
||
|
stack.add('Z');
|
||
|
state = 1;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
break;
|
||
|
case 1:
|
||
|
if (symbol == 'Z' && stackSymbol == 'Z') {
|
||
|
stack.add('Z');
|
||
|
stack.add('Z');
|
||
|
state = 2;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
break;
|
||
|
case 2:
|
||
|
if (symbol == 'O' && stackSymbol == 'Z') {
|
||
|
state = 3;
|
||
|
} else if (symbol == 'Z' && stackSymbol == 'Z') {
|
||
|
stack.add('Z');
|
||
|
stack.add('Z');
|
||
|
state = 2;
|
||
|
} else if (symbol == 'Z' && stackSymbol == '$') {
|
||
|
stack.add('$');
|
||
|
stack.add('Z');
|
||
|
state = 2;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
break;
|
||
|
case 3:
|
||
|
if (symbol == 'O' && stackSymbol == 'Z') {
|
||
|
state = 3;
|
||
|
} else if (symbol == 'Z' && stackSymbol == 'Z') {
|
||
|
stack.add('Z');
|
||
|
stack.add('Z');
|
||
|
state = 2;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (state == 3 && stack.size() >= 1 && stack.remove(stack.size() - 1) == 'Z') {
|
||
|
state = 4;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
if (state == 4 && stack.size() >= 1 && stack.remove(stack.size() - 1) == '$') {
|
||
|
state = 5;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
if (state == 5) {
|
||
|
accept(word);
|
||
|
return true;
|
||
|
} else {
|
||
|
dontAccept(word);
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
private static void dontAccept(String word) {
|
||
|
System.out.println("Word: " + word + "\nnot accepted");
|
||
|
}
|
||
|
|
||
|
private static void accept(String word) {
|
||
|
System.out.println("Word: " + word + "\naccepted ");
|
||
|
}
|
||
|
|
||
|
}
|