以下は、DFA (決定論的有限オートマトン) を実装する簡単なプログラムです。ただし、私の問題には DFA は関係ありません。
#include<iostream>
using namespace std;
int main()
{
char c;
int state=1;
while((c=cin.get())!='4')
{
switch(state)
{
case 1:
if(c=='0')
state=2;
if(c=='1')
state=1;
if(c=='2')
state=2;
break;
case 2:
if(c=='0')
state=5;
if(c=='1')
state=1;
if(c=='2')
state=3;
break;
case 3:
if(c=='0')
state=1;
if(c=='1')
state=5;
if(c=='2')
state=4;
break;
case 4:
if(c=='0')
state=3;
if(c=='1')
state=4;
if(c=='2')
state=5;
break;
case 5:
if(c=='0')
state=5;
if(c=='1')
state=4;
if(c=='2')
state=1;
break;
default:
cout<<"Input will not be accepted"<<endl;
} //switch
cout<<"Current state is "<<state<<endl;
} //while
return 0;
}
コードを実行すると、すべての行が 2 回出力されていることがわかりました。たとえば、0 1 0 0 4 と入力すると、DFA は 1->2->1->2->5 の状態になるため、出力は次のようになります。
Current state is 2
Current state is 1
Current state is 2
Current state is 5
しかし、出力は次のとおりです。
Current state is 2
Current state is 2
Current state is 1
Current state is 1
Current state is 2
Current state is 2
Current state is 5
Current state is 5
誰でも原因を指摘できますか?