Skip to content

Instantly share code, notes, and snippets.

@rohitdwivedula
Last active January 14, 2020 11:26
Show Gist options
  • Save rohitdwivedula/557e9e650fc616019c9793edc8862ec0 to your computer and use it in GitHub Desktop.
Save rohitdwivedula/557e9e650fc616019c9793edc8862ec0 to your computer and use it in GitHub Desktop.
Logo Implementation Using Flex
%{
#include <math.h>
#define PI 3.14159
float distance = 0;
float location[2]; // current coordinates (x, y)
float angle_x = PI/2; // current angle with positive X-axis
double displacement(double x, double y){
return sqrt(x*x + y*y);
}
%}
DIGIT [0-9]
ALPHABET [A-Za-z]
SPACE ' '
%%
STOP {return 0;}
FD" "({DIGIT}*"."{DIGIT}+|{DIGIT}+) {
float temp = atof(&yytext[3]);
printf("MOVE FORWARD BY %f UNITS\n", temp);
location[0] += cos(angle_x) * temp;
location[1] += sin(angle_x) * temp;
distance += temp;
printf("NEW LOCATION: (%f, %f)\n", location[0], location[1]);
}
BK" "({DIGIT}*"."{DIGIT}+|{DIGIT}+) {
float temp = atof(&yytext[3]);
printf("MOVE BACKWARD BY %f UNITS\n", temp);
location[0] -= cos(angle_x) * temp;
location[1] -= sin(angle_x) * temp;
distance += temp;
printf("NEW LOCATION: (%f, %f)\n", location[0], location[1]);
}
RT" "({DIGIT}*"."{DIGIT}+|{DIGIT}+) {
float temp = atof(&yytext[3]);
printf("TURN RIGHT BY %f DEGREES\n", temp);
angle_x -= (temp * PI)/180;
printf("Angle with +X Axis: %f degrees\n", (180/PI) * angle_x);
}
LT" "({DIGIT}*"."{DIGIT}+|{DIGIT}+) {
float temp = atof(&yytext[3]);
printf("TURN LEFT BY %f DEGREES\n", temp);
angle_x += (temp * PI)/180;
printf("Angle with +X Axis: %f degrees\n", (180/PI) * angle_x);
}
{DIGIT}*"."{DIGIT}+ {
printf("Floating point number %s (%f)\n", yytext, atof(yytext));
}
{DIGIT}+ {
printf("An integer %s, (%d)\n", yytext, atoi(yytext));
}
SPACE { /** Do nothing **/ }
{ALPHABET}+ {printf("[ERROR] Don't know how to %s.\n", yytext);}
%%
int yywrap(){}
int main(){
yylex();
printf("\nTotal distance - %f\n", distance);
printf("\nTotal displacement - %f\n", displacement(location[0], location[1]));
return 0;
}
FILENAME=$1
flex $FILENAME
gcc lex.yy.c -lm
./a.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment