Advertisement
Guest User

Untitled

a guest
May 25th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. #include <unistd.h>
  6. #include <map>
  7. #include <algorithm>
  8.  
  9. using std::string;
  10. using std::vector;
  11. using std::map;
  12. using std::ifstream;
  13.  
  14.  
  15. class state_machine {
  16.     string start;
  17.     vector<string> final_states;
  18.     vector<string> states;
  19.     vector<bool> alphabet;
  20.     map<char, map<string, string> > transisions;
  21.  
  22. public:
  23.     state_machine(const std::string& filename)
  24.         : alphabet(256, 0)
  25.     {
  26.         ifstream fs(filename);
  27.         fs >> start;
  28.         int n;
  29.         fs >> n;
  30.         final_states.resize(n);
  31.         for (int i = 0; i < n; ++i) {
  32.            fs >> final_states[i];
  33.         }
  34.         fs >> n;
  35.         for (int i = 0; i < n; ++i) {
  36.             string s, f;
  37.             char c;
  38.             fs >> c >> s >> f;
  39.             alphabet[c] = true;
  40.             transisions[c][s] = f;
  41.         }
  42.     }
  43.  
  44.     bool check(const string& input) const {
  45.         string curr_state = start;
  46.         for (char i : input) {
  47.             if (!alphabet[i])
  48.                 return false;
  49.             auto tit = transisions.find(i);
  50.             if (tit == transisions.end()) {
  51.                 return false;
  52.             }
  53.             auto qit = tit->second.find(curr_state);
  54.             if (qit == tit->second.end()) {
  55.                 return false;
  56.             }
  57.             curr_state = qit->second;
  58.         }
  59.         if (find(final_states.begin(), final_states.end(), curr_state) != final_states.end()) {
  60.                 return true;
  61.         }
  62.         return false;
  63.     }
  64. };
  65.  
  66.  
  67. void usage(char *argv[]) {
  68.     std::cerr << "Usage: " << argv[0] << " -f filename\n";
  69.  
  70. }
  71.  
  72. int main(int argc, char *argv[]) {
  73.     std::string filename;
  74.     char opt;
  75.     while ((opt = getopt(argc, argv, "f:")) != -1) {
  76.         switch (opt) {
  77.             case 'f':
  78.                 filename = optarg;
  79.                 break;
  80.             default:
  81.                 usage(argv);
  82.                 return 1;
  83.         }
  84.     }
  85.     if (filename.size() == 0) {
  86.         std::cerr << "Missed required argument -f\n";
  87.         usage(argv);
  88.         return 1;
  89.     }
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement