Aufgabe1_KellerautomatTest erstellt.

This commit is contained in:
romanschenk37 2022-04-03 21:16:05 +02:00
parent 7cbe6169ee
commit 5309a7a555
2 changed files with 124 additions and 0 deletions

View File

@ -0,0 +1,19 @@
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Aufgabe1_KellerautomatTest {
@Test
void calculate() {
String[] acceptableWords = {"ZZO", "ZZOZZOO", "ZZZOO"};
for (String word : acceptableWords) {
assertTrue(Aufgabe1_Kellerautomat.calculate(word));
}
String[] notAcceptableWords = {"ZZOO", "ZZOZZO", "ZOZ"};
for (String word : notAcceptableWords) {
assertFalse(Aufgabe1_Kellerautomat.calculate(word));
}
}
}

View File

@ -0,0 +1,105 @@
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 ");
}
}