Monday, November 21

Lex- Collect Tokens and sort

Hello friend,
  Here I am with an interesting Lex program which sorts all the nubers from input file and sort them. If you are well-familiarised with lex paradigm, it is very easy task.

Things to remember:
  • The definition [0-9]+ can detect all the numbers from input
  • The number detected at present will be pointed by yytext and have length yyleng
  • Whenever a new token (here a number) is detected, yytext will be replaced with new value. 
Logic
  1. Read the input
  2. If a number is detected, store it in an array (we can use yytext and yyleng for this). Read each digit --> multiply with 10 --> add next digit -->continue upto last digit.
  for eg, to read 123
initialise num=0;
  • read 1--> num=num*10+1-->num=0+1-->num=1
  • read 2--> num=num*10+2-->num=10+2-->num=12
  • read 3--> num=num*10+3-->num=120+3-->num=123
store num in an array.
3. After reading all the numbers, sort the number within the array




%{
#include<stdio.h>
int t, a[20],i,j,n,num;
%}
%%
[0-9]+ {num=0;
 for(i=0;i<yyleng;i++)
num=num*10+(yytext[i]-'0');

a[n++]=num;
}
. ;
%%
main()
{
yyin=fopen("file.c","r");
yylex();
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
for(i=0;i<n;i++)
printf("%d\n",a[i]);

}

int yywrap()
{
return 1;
}





sample input (in file.c)
main()
{
int i=9, j=900,k=115;
printf("%d,i+j+k);
}




output
9
115
900

3 comments :

Sushil Kumar said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Instead of converting the number yourself we can use atoi() function to get the job done.

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Thanks a lot for sharing.Very helpful
web designing oman

v!p!n said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Welcome Suhayla Adara Almasi

Post a Comment