Skip to content

Instantly share code, notes, and snippets.

@okaram
Created June 7, 2013 18:10
Show Gist options
  • Save okaram/5731216 to your computer and use it in GitHub Desktop.
Save okaram/5731216 to your computer and use it in GitHub Desktop.
Finite State Machines (Automatas) in C++
bool accepts(string str)
{
return contains(F,delta_hat(q0,str));
}
template<typename T>
bool contains(const set<T>& all,const T& elem)
{
return all.find(elem) != all.end();
}
unsigned delta1(unsigned state, char input)
{
if(state==0)
if (input=='1')
return 0;
else // input=='0'
return 1;
else {// state==1
return 1;
}
}
State_T delta_hat(State_T q, string str)
{
State_T theState=q;
for(char c : str) {
cout << "at " << theState << " seeing " << c ;
theState=delta(theState,c);
cout << " went to " << theState << endl;
}
return theState;
}
template<typename State_T>
struct DFA {
set<State_T> Q,F; // all states, and accepting states
State_T q0; // the starting state
set<char> sigma;
std::function<State_T(State_T, char)> delta;
...
};
int main(int argc, char* argv[])
{
set<unsigned> Qs {0,1};
set<unsigned> Fs {1};
set<char> Sigma {'0','1'};
DFA<unsigned> dfa1=DFA<unsigned>(Qs,Fs,0,Sigma,delta1);
int from=atoi(argv[1]);
string str(argv[2]);
cout << dfa1.delta_hat(from,argv[2]) << endl;
cout << boolalpha << dfa1.accepts(str) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment