Skip to content
Related Articles

Related Articles

Improve Article

LEX Code which accepts string containing third last element ‘a’ over input alphabet {a, b}

  • Difficulty Level : Hard
  • Last Updated : 05 Jul, 2021
Geek Week

In this article, we will discuss the DFA in LEX Code which accepts a string containing the third-last element ‘a’ over input alphabet {a, b} with the help of example. Let’s discuss it one y one.

Pre-requisite – Designing Finite Automata

Problem Overview : 
Design a DFA in LEX Code which accepts a string containing third-last element ‘a’ over input alphabet {a, b}. 

Example –

Input : aaab
Output: Accepted

Input : ab
Output: Not Accepted

Input: ababab
Output:Not Accepted

Input:123
Output:Invalid

Input:bbba
Output:Not Accepted

Input:bbbaaab
Output:Accepted

Approach :
LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define eight more states: A, B, C, D, E, F, G, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and the print message “Invalid”. If the input string ends at state INITIAL, A, B or F then display a message “Not Accepted”. Else if the input string ends at state C, D, E, or G then displays otherwise, a message “Accepted”.



Note –
So to compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with .l extension. For example- filename.l Then after saving the program closes the lex file and then open the terminal and write the following commands as follows.

lex filename.l
cc lex.yy.c
./a.out

LEX Code : 

%{
%}
%s A B C D E F G DEAD
%%
<INITIAL>b BEGIN INITIAL;
<INITIAL>a BEGIN A;
<INITIAL>[^ab\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}

<A>b BEGIN F;
<A>a BEGIN B;
<A>[^ab\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}

<B>b BEGIN D;
<B>a BEGIN C;
<B>[^ab\n] BEGIN DEAD;
<B>\n BEGIN INITIAL; {printf("Not Accepted\n");}

<C>b BEGIN D;
<C>a BEGIN C;
<C>[^ab\n] BEGIN DEAD;
<C>\n BEGIN INITIAL; {printf("Accepted\n");} 

<D>b BEGIN G;
<D>a BEGIN E;
<D>[^ab\n] BEGIN DEAD;
<D>\n BEGIN INITIAL; {printf("Accepted\n");}

<E>b BEGIN F;
<E>a BEGIN B;
<E>[^ab\n] BEGIN DEAD;
<E>\n BEGIN INITIAL; {printf("Accepted\n");}

<F>b BEGIN G;
<F>a BEGIN E;
<F>[^ab\n] BEGIN DEAD;
<F>\n BEGIN INITIAL; {printf("Not Accepted\n");}

<G>b BEGIN INITIAL;
<G>a BEGIN A;
<G>[^ab\n] BEGIN DEAD;
<G>\n BEGIN INITIAL; {printf("Accepted\n");}

<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}
 
%%
int yywrap()
{
 return 1;
}
int main()
{
 printf("Enter String\n");
 yylex();
 return 0;
}

Output :

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :