码迷,mamicode.com
首页 > 其他好文 > 详细

DFA编程练习2

时间:2021-01-25 11:32:58      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:code   str   rect   class   The   题目   point   nta   des   

  • 题目: 请设计DFA, 使其接受全部含有奇数个1的串, 假定 ∑ = {0, 1}.

解:

DFA可能出现两个个状态:

  1. qeven: 读入了偶数个1的串.
  2. qodd: 读入了奇数个1的串, 该状态也是终结状态(accept state).

它们的状态转移图如下:

技术图片

编写程序, 运行效果如下:

技术图片

测试用例说明:

  1. 0000不被上图的DFA接受
  2. 1111不被上图的DFA接受
  3. 1符合题目要求, 被DFA接受
  4. 0011001符合题目要求, 被DFA接受
  5. 空串不被DFA接受
  6. 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);
}

DFA编程练习2

标签:code   str   rect   class   The   题目   point   nta   des   

原文地址:https://www.cnblogs.com/laplaceB/p/14318876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!