# CMPSCI 311: Theory of Algorithms

### Counting Strings in a Regular Language

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");}
``````

• Question 1: What is the running time of `accept` on a string of length n, assuming that k is a constant? Explain your answer.

• Question 2: For the DFA given in the main method, how many strings of length eight are in its language? (You may want to start by counting smaller strings.)

• Question 3: Write a method `census` for the `Dfa` class that takes an ```int parameter n and returns the number of strings of length n in the DFA's language. There is a slow way to do this by brute force, and a more clever way. Try to do both. Analyze the running time of your methods in terms of n, again assuming that k is a constant. ```
``` Last modified 29 October 2003 ```