編程模擬自動機的實現方法(用狀態轉換圖)

算法如下:

State=i;
Nextchar(ch);
While(state!=error&&ch!=EOF)
 switch (state)     {
Case i: switch(ch)  {
       case a: state=j;  break;
       case b: state=k;  break;
       }
Case j: switch(ch)  {…..}
}
If (state是終止狀態 and ch=EOF) print(OK);
   else  print(error);

 

 

(a|b)*ab  實驗

 

C語言實現代碼如下:

 

#include<stdio.h>

#define N 1000

 

void main()

{

   char state='A';

   char ch[N];

   int n,m;

   printf("請輸入由 ab字母組成的字符串:/n");

   gets(ch);

  

 

   for(n=0;ch[n];n++)

   {

    if(ch[n]=='a'|| ch[n]=='b')

    {

 

s:      switch(state)

      {

         case 'A': switch(ch[n]){

            case 'a': state='B'; break;

            case 'b': state='A'; continue;

                 } break;

 

         case 'B': switch(ch[n]){

            case 'a': state='B'; continue;

            case 'b': state='D'; break;

                 } break;

 

         case 'C': switch(ch[n]){

            case 'a': state='B'; break;

            case 'b': state='A'; break;

                 } break;

 

            case 'D':goto h;

      }

    }

   

    else if(ch[n]==' ')

    {

       for(m=n+1;ch[m]!='/0';m++)

       {

            ch[m-1]=ch[m];   

       }

       for(n=0;ch[n];n++)

           ch[n]=ch[m];

       goto s;

    }

 

    else

       printf("please input a||b/n");

   }

 

 

   h:   if( (state=='D')&&(ch[n--]=='/0') )

           printf("可被接受/n");

        else

           printf("不可被接受/n");

 

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章