編譯原理DFA(有限確定自動機)的構造


CODE: https://github.com/pxjw/Principles-of-Compiler/tree/master/consDFA

原題:

1、自己定義一個簡單語言或者一個右線性正規文法

示例如(僅供參考)  G[S]:S→aU|bV    U→bV|aQ  

V→aU|bQ     Q→aQ|bQ|e

2、構造其有窮確定自動機,如


3、利用有窮確定自動機M=(K,Σ,f, S,Z)行為模擬程序算法,來對於任意給定的串,若屬於該語言時,該過程經有限次計算后就會停止並回答“是”,若不屬於,要么能停止並回答“不是”      

K:=S;

c:=getchar;

while c<>eof do

{K:=f(K,c);  

  c:=getchar;       };

if K is in Z then return (‘yes’)

                  else return (‘no’)

 

開始編程!

1.狀態轉換式構造類:
current——當前狀態
next——下一狀態

class TransTile
{
public:
    char current;
    char next;
    char input;
    TransTile(char C,char I,char Ne){
        current = C;
        next = Ne;
        input = I;
    }
};

 

2.DFA的構造類

此處包括DFA的數據集,字母表,以及過程P的定義。

包括了初始化,遍歷轉換,以及最終的字符串識別。

class DFA
{
public:
    //構造狀態集各個元素
    string States;
    char startStates;
    string finalStates;
    string Alphabets;
    vector <TransTile> Tile;
    
    DFA(){
        init();
    }
    void init()
    {
        cout << "輸入有限狀態集S:" << endl;
        cin >> States;
        cout << "輸入字符集A:" << endl;
        cin >> Alphabets;
        cout << "輸入狀態轉換式(格式為:狀態-輸入字符-下一狀態,輸入#結束):" << endl;
        cout << "例如:1a1 \n 1a0 \n 2a1 \n #" << endl;
        int h = 0;

        //while (cin>>input){
        //    TransTile transval(input[0], input[1], input[2]);
        //    Tile.push_back(transval);
        //}
        while(true){
            char input[4];
            cin>>input;
            if(strcmp(input,"#")==0)
                break;
            TransTile transval(input[0],input[1],input[2]);
            Tile.push_back(transval);
        }
        cout << "輸入初態:" << endl;
        cin >> startStates;
        cout << "輸入終態:" << endl;
        cin >> finalStates;
    }
    //遍歷轉換表
    char move(char P,char I){
        for (int i = 0; i < Tile.size(); i++){
            if (Tile[i].current == P&&Tile[i].input == I){
                return Tile[i].next;
            }    
        }
        return 'E';
    }
    //識別字符串函數
    void recognition(){
        string str;
        cout << "輸入需要識別的字符串:" << endl;
        cin >> str;
        int i = 0;
        char current = startStates;
        while (i < str.length()){
            current = move(current, str[i]);
            if (current == 'E'){
                break;
            }
            i++;
        }
        if (finalStates.find(current) != finalStates.npos){
            cout << "該自動機識別該字符串!" << endl;
        }
        else
        {
            cout << "該自動機不能識別該字符串!" << endl;
        }
    }
};

 

3.測試

Main函數

int main(){
    DFA dfa;    
    bool tag;

    while(1){
        cout<<"你想要繼續嗎?是請輸入1,否輸入0:"<<endl;
        cin>>tag;
        if(tag){
            dfa.recognition();
        }else
            break;

    }
    return 0;
}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM