📜  LEX代码中的DFA,它接受偶数个零和偶数个1(1)

📅  最后修改于: 2023-12-03 15:17:18.997000             🧑  作者: Mango

DFA for Accepting Even Zeros and Even Ones in LEX Code

In this article, we will discuss how to write a DFA in LEX code that will accept only those strings that contain even number of zeros and even number of ones.

What is DFA?

DFA stands for Deterministic Finite Automaton, which is a mathematical model for a finite-state machine. It is a formalism used to recognize languages in automata theory. DFA is a graph-like structure that has a fixed number of states, and each state is labeled with a unique input symbol. DFA reads input symbols and transitions between states, starting from an initial state and ending in a final state.

Creating a DFA for Even Zeros and Even Ones

The DFA for accepting even zeros and even ones can be created using the following steps:

  1. Identify the input symbols. In this case, the input symbols are 0 and 1.
  2. Define the states of the DFA. We need to create four states to accept strings that have even number of zeros and even number of ones.
  3. Define the transitions between the states. We need to define transitions for each input symbol based on the current state.
  4. Define the starting state and final state of the DFA.

Here is the LEX code for the DFA that accepts even number of zeros and even number of ones:

%{
#include <stdio.h>
int count0 = 0, count1 = 0;
%}

%%

0 { count0++; }
1 { count1++; }
\n {
    if (count0 % 2 == 0 && count1 % 2 == 0) {
        printf("Accepted\n");
    } else {
        printf("Rejected\n");
    }
    count0 = count1 = 0;
}

%%

int main() {
    yylex();
    return 0;
}
Explanation

The above code uses three important LEX directives:

  1. The %{...%} section is a C code block that is copied verbatim to the generated lexer file.
  2. The %% section is used to define the rules for matching input patterns and producing output actions.
  3. The %option noyywrap directive indicates that LEX should not generate a default yywrap() function.

The DFA starts in the initial state, which has no label, and keeps track of the number of zeros and ones encountered in the input string by incrementing the count0 and count1 variables. When a newline character is encountered, the DFA checks whether the count of zeros and ones is even. If both are even, the input string is accepted; otherwise, it is rejected.

Conclusion

In this article, we have discussed how to write a DFA in LEX code that accepts even number of zeros and even number of ones. The DFA recognizes the input string based on the current state and the transitions between the states. We hope this article has provided you with a good understanding of DFA and how to create one in LEX code.