标签:code str rect class The 题目 point nta des
解:
DFA可能出现两个个状态:
1
的串.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 <stdio.h>
#include <stdlib.h> // calloc()
#include <string.h>
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!\n");
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\n", s);
printf("FSM don‘t accept this string\n");
free(myFsm);
exit(0);
}
标签:code str rect class The 题目 point nta des
原文地址:https://www.cnblogs.com/laplaceB/p/14318876.html