题目: 请设计DFA, 使其接受全部含有奇数个1的串, 假定 ∑ = {0, 1}.
解:
DFA可能出现两个个状态:
qeven: 读入了偶数个1的串.
qodd: 读入了奇数个1的串, 该状态也是终结状态(accept state).
它们的状态转移图如下:
编写程序, 运行效果如下:
测试用例说明:
0000不被上图的DFA接受
1111不被上图的DFA接受
1符合题目要求, 被DFA接受
0011001符合题目要求, 被DFA接受
空串不被DFA接受
0不被上图DFA接受
程序代码如下:
/* FSM-example2.c
* Using Deterministic Finite Automaton to recongnize
* a `0-1 string`
*
* Example2: Please design a DFA, accept every string
* containing odd numers of 1.
**/
#include
#include // calloc()
#include
enum {
STATE_even = 1, // Even number of 1 has readed
STATE_odd, // Odd number of 1 has readed
STATE_T // Accept state
};
typedef struct fsm_st {
int state;
int pos; // point to current pos
char buf[BUFSIZ];
}fsm_st;
fsm_st* myFsm;
void FSMdriver(fsm_st*);
void Hault(int);
int main() {
/* Create a FSM and initialize */
myFsm = (fsm_st*)calloc(0x1, sizeof(myFsm));
myFsm->state = STATE_even;
myFsm->pos = 0;
/* Read a string */
printf("Input a 01-string: ");
fgets(myFsm->buf, BUFSIZ, stdin);
/* Strat FSM */
while( myFsm->state != STATE_T ) {
FSMdriver(myFsm);
}
printf("Accept string!
");
free(myFsm);
return 0;
}
void FSMdriver(fsm_st* me) {
int pos = me->pos;
switch(me->state) {
case STATE_even:
if( me->buf[pos] == ‘1‘ ) {
me->state = STATE_odd;
me->pos++;
} else if( me->buf[pos] == ‘0‘ ) {
me->state = STATE_even;
me->pos++;
} else {
Hault(STATE_even);
}
break;
case STATE_odd:
if( me->buf[pos] == ‘0‘ ) {
me->state = STATE_T; // Terminated correctly
me->pos++;
} else if( me->buf[pos] == ‘1‘ ) {
me->state = STATE_even;
me->pos++;
} else {
me->state = STATE_T; // At the end stay in STATE_odd
}
break;
}
}
void Hault(int s) {
printf("FSM hault in STATE_%d
", s);
printf("FSM don‘t accept this string
");
free(myFsm);
exit(0);
}
DFA编程练习2