Modelling a Finite Deterministic Automaton via this data

好久不见. 提交于 2019-11-29 15:50:11

I'd say that the most natural representation is to model each state as a Map with alphabet symbols as keys and resulting states (i.e. Map instances) as values. A class to represent an automaton would have a reference for the initial state, one for the current state, a Set of states and a Set of final states. Oh, and a Set for the alphabet.

The above should give you good performance for all relevant operations. Add some methods for convenience and encapsulation and you're done.

Edit:

You need a State class to be able to use generics correctly:

public class State extends HashMap<Character, State>{ }

public class Automaton{ 
    private Set<State> allStates;
    private Set<State> finalStates;
    private State initialState;
    private State currentState;
    private Set<Character> alphabet;

    public boolean doTransition(Character input)){
        if(!alphabet.contains(input){ 
            throw new IllegalArgumentException();
        }
        if(finalStates.contains(currentState)){ 
            throw new IllegalStateException(); 
        }

        currentState = currentState.get(input);

        if(currentState == null){ 
            throw new IllegalStateException(); 
        }

        return finalStates.contains(currentState);
    }

    // more methods go here
}

For the 3 state automaton you used as example:

State s0 = new State();
State s1 = new State();
State s2 = new State();
s0.put('a', s1);
s0.put('b', s0);
s1.put('a', s2);
s1.put('b', s0);
s2.put('a', s2);
s2.put('b', s0);

This should happen through initialization methods of the Automaton class, of course.

That is a fun project.

You might want to think about the interface around your FSM first. How do you program it? How do you feed it?

Something like:

fsm.setStates("ab");
fsm.setInitialState(0);
fsm.addTransition(1,0);
fsm.addTransition(2,0);
fsm.addTransition(2,0);
fsm.setFinalState...

If you have something simple like this, it'll separate your code out and make it much easier for you to think of just one section at a time (your "UI" section, which is parsing the input and passing it to the FSM, should become trivial) This just leaves the question you ACTUALLY asked: how to implement the FSM.

There are probably a million ways, but I think the easiest to reference and work with has to be an int[][]; the transition syntax will be clear and straight forward like:

newState=table[oldState][transition];

once you've populated the array.

But remember to break your code apart and think of how you want to access the classes, not just what's the next step in the code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!