Created
June 7, 2013 18:10
-
-
Save okaram/5731216 to your computer and use it in GitHub Desktop.
Finite State Machines (Automatas) in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool accepts(string str) | |
{ | |
return contains(F,delta_hat(q0,str)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
bool contains(const set<T>& all,const T& elem) | |
{ | |
return all.find(elem) != all.end(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unsigned delta1(unsigned state, char input) | |
{ | |
if(state==0) | |
if (input=='1') | |
return 0; | |
else // input=='0' | |
return 1; | |
else {// state==1 | |
return 1; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
... | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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