DFA.java


Below is the syntax highlighted version of DFA.java from §7.3 Finite State Automata.


/*************************************************************************
 *  Compilation:  javac DFA.java
 *  Execution:    java DFA
 *  
 *  Simulate a DFA which recognizes the language of all bitstrings with
 *  a multiple of three b's.
 *
 *  % java DFA babbabbb
 *  true
 *
 *  % java DFA baabbba
 *  false
 *
 *************************************************************************/

public class DFA {
    public static void main(String[] args) {
        String input = args[0];
        boolean[] accept = { true, false, false };
        int[][] next = { { 0, 1 },
                         { 1, 2 },
                         { 2, 0 }
                       };
        int state = 0;
        for (int i = 0; i < input.length(); i++) {
            state = next[state][input.charAt(i) - 'a'];
        }
        System.out.println(accept[state]);
    }
}   


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.