CMPSCI 311: Theory of Algorithms

David Mix Barrington

Fall, 2003

Discussion Notes #7

from Wednesday 29 Oct 2003

Counting Strings in a Regular Language

Please answer the questions during the discussion period.

Remember that a DFA is a machine that reads a string and decides whether it is in a particular language by maintaining a state from a finite state set. Here is a Java class modeling DFA's whose input is strings over the alphabet {a,b}:

     public class Dfa
        int k; // number of states
        bool [] isFinal; // whether each state is final
        int [] atrans, btrans; // transitions for a, b: atrans[i] is delta(a,i)
        int state; //current state, note start state is always 0

     public Dfa (int [] fin, int [] at, int [] bt)
     {// creates new DFA with given final states, transformations
        k = fin.length;
        if ((at.length != k) || (bt.length != k))
           throw new ArithmeticException ("DFA constructor : bad input");
        isFinal = fin; atrans = at; btrans = bt;
        state = 0;}

     public boolean accept (String w)
     {// returns true iff this DFA accepts w, w must be in {a,b}*
        state = 0;
        for (int i=0; i < w.length(); i++) {
           if (w.charAt(i) == 'a') state = atrans[state];
           else if (w.charAt(i) == 'b') state = btrans[state];
           else throw new ArithmeticException("DFA: bad input string");}
        return isFinal[state];}

     public static void main (String[] args)
     {// creates sample Dfa with three states, tests it
        Dfa d = new Dfa({false, true, false}, {0,1,2}, {1,2,0});
        System.out.println("It is " + d.accept("abbabbaa") +
                           " that abbabbaa is in the language");}

Last modified 29 October 2003