Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.List;
- import java.util.ListIterator;
- public class TuringMachine {
- //region Fields
- private List<String> alphabet;
- private List<String> tape;
- private ListIterator<String> carriage;
- private List<State> states;
- //endregion
- public TuringMachine() {
- alphabet = new ArrayList<>() {{
- add(" ");
- }};
- tape = new ArrayList<>(Collections.nCopies(200, " "));
- carriage = tape.listIterator(tape.size() / 2);
- states = new ArrayList<>();
- }
- public void setAlphabet(String... alphabet) {
- Arrays.stream(alphabet).forEach(this::alphabetAdd);
- }
- private void alphabetAdd(String word) {
- if (!alphabet.contains(word))
- alphabet.add(word);
- }
- public void addWord(String word) {
- if (!alphabet.contains(word))
- throw new IllegalArgumentException();
- tape.add(word);
- }
- public void addAllWords(String... words) {
- Arrays.stream(words).forEach(this::addWord);
- }
- public static class State {
- //region Fields
- private String[] forWords;
- private String[] words;
- private String[] transitions;
- private int[] doubleStates;
- private int index;
- private static int nextIndex;
- //endregion
- public State(String[] forWords, String[] words, String[] transitions, int[] doubleStates) {
- this.forWords = forWords;
- this.words = words;
- this.transitions = transitions;
- this.doubleStates = doubleStates;
- index = ++nextIndex;
- }
- public static int getIndex() {
- return nextIndex;
- }
- }
- public void addState(String[] forWords, String[] words, String[] transitions, int[] doubleStates) {
- checkWords(forWords);
- checkWords(words);
- checkTransitions(transitions);
- checkDoubleStates(doubleStates);
- states.add(new State(forWords, words, transitions, doubleStates));
- }
- private void checkWords(String[] words) {
- Arrays.stream(words).forEach(word -> {
- if (!alphabet.contains(word))
- throw new IllegalArgumentException();
- });
- }
- private void checkTransitions(String[] transitions) {
- Arrays.stream(transitions).forEach(transition -> {
- switch (transition) {
- case "<":
- case ">":
- case ".": break;
- default:
- throw new IllegalArgumentException();
- }
- });
- }
- private void checkDoubleStates(int[] doubleStates) {
- Arrays.stream(doubleStates).forEach(doubleState -> {
- if (doubleState > State.getIndex())
- throw new IllegalArgumentException();
- });
- }
- public List<String> run() {
- return tape;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement