Implementing A DFA (Deterministic Finite Automata) in C++
Implementing A DFA (Deterministic Finite Automata) in C++
Theory
In DFA, for each input symbol, one can determine the state to which the machine will move.
Hence, it is called Deterministic Automaton. As it has a finite number of states, the machine
is called Deterministic Finite Machine or Deterministic Finite Automaton.
• q0 is the initial state from where any input is processed (q0 ∈ Q).
1. Make a DFA.
3 states.
q0 -> Initial State
q1 -> Final State
4. Choose 2 strings
These strings are checked for acceptance by using them as input for the DFA that we
will create on the computer.
The results of their acceptance will give us an intuition on whether the DFA is
working correctly or not.
Code
#include<iostream>
#include<string>
using namespace std;
int main()
{
int table[3][2] = {{2, 1}, {1, 1}, {2, 2}};
string input;
int state = 0;
cout<<"Transitions: \n";
for(int i = 0; i < input.length(); i++)
{
cout<<"(q"<<state<<", "<<input[i]<<") -> q";
state = table[state][input[i] - '0'];
cout<<state<<endl;
}
if(state == 1)
cout<<"\nString accepted!";
else
cout<<"\nNot accepted!";
return 0;
}
Output
#1
#2
Discussion and Result
As it can be seen from the output obtained, we get the result that we expected.
W = 10011 was accepted by the DFA as it starts with 1, while,
W = 0011 was not accepted by it as it starts with 0 and not 1.
The automaton takes a finite sequence of 0s and 1s as input. For each state, there is a
transition arrow leading out to a next state for both 0 and 1. Upon reading a symbol, a DFA
jumps deterministically from one state to another by following the transition arrow.
For example, if the automaton is currently in state q0 and the current input symbol is
1, then it deterministically jumps to state q1.
A DFA has a start state (denoted graphically by an arrow coming in from nowhere)
where computations begin, and a set of accept states (denoted graphically by a
double circle) which help define when a computation is successful.
For example, a DFA can model software that decides whether or not online user input
such as email addresses are valid.
DFAs recognize exactly the set of regular languages, which are, among other things, useful
for doing lexical analysis and pattern matching.