-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutomaton.java
88 lines (69 loc) · 2.32 KB
/
Automaton.java
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
package machine;
import machine.exceptions.FirstStateException;
import machine.exceptions.InvalidTape;
import machine.exceptions.TransitionNotFound;
import machine.transition.Action;
import machine.transition.Direction;
public class Automaton {
private State[] states;
private char[] tape;
private State firstState;
private int symbolIndex = 0;
private char actualSymbol;
private State actualState;
public Automaton(State[] states, String tape) throws FirstStateException, InvalidTape {
this.states = states;
this.tape = tape.toCharArray();
if (this.tape.length == 0)
throw new InvalidTape();
this.actualSymbol = this.tape[this.symbolIndex];
this.getFirstState();
this.actualState = this.firstState;
}
private void getFirstState() throws FirstStateException {
for (State state : this.states) {
if (state.isFirst()) {
this.firstState = state;
return;
}
}
throw new FirstStateException();
}
private void move(Direction direction) {
if (direction == Direction.LEFT)
this.moveLeft();
else
this.moveRight();
}
private void moveRight() {
this.symbolIndex++;
}
private void moveLeft() {
this.symbolIndex--;
}
private void updateActualSymbol() throws ArrayIndexOutOfBoundsException {
this.actualSymbol = this.tape[this.symbolIndex];
}
public boolean test() throws TransitionNotFound {
while (true) {
Action transitionResult = this.makeTransition();
this.actualState = transitionResult.getNext();
this.write(transitionResult.getWrite());
this.move(transitionResult.getDirection());
try {
this.updateActualSymbol();
} catch (ArrayIndexOutOfBoundsException error) {
return transitionResult.getReachedFinal();
}
}
}
private Action makeTransition() throws TransitionNotFound {
return this.actualState.test(this.actualSymbol);
}
private void write(char newSymbol) throws ArrayIndexOutOfBoundsException {
this.tape[this.symbolIndex] = newSymbol;
}
public String getTape() {
return new String(this.tape);
}
}