Skip to content

Instantly share code, notes, and snippets.

@iCHAIT
Created Aug 18, 2015
Embed
What would you like to do?
Accept string for a finite automata using automata from txt file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *fp;
int init, *FS, **FA, i, j, col, row, fs, r, c;
char *str, temp[50];
fp = NULL;
FA = NULL;
FS = NULL;
str = NULL;
fp = fopen("automata.txt", "r");
fscanf(fp, "%d", &init);
fgets(temp, sizeof(char)*50, fp);
fgets(temp, sizeof(char)*50, fp);
str = temp;
i = 0;
while(*str != '\0')
{
FS = (int *) realloc(FS, sizeof(int)*(i+1));
sscanf(str, "%d", &FS[i++]);
str++;
while(isdigit(*str))
{
str++;
}
while(isspace(*str))
str++;
}
fs = i;
fgets(temp, sizeof(char)*50, fp);
str = temp;
i= 0;
FA = (int **) malloc(sizeof(int *)*1);
FA[0] = NULL;
while(*str != '\0')
{
FA[0] = (int *)realloc(FA[0], sizeof(int)*(i+1));
sscanf(str, "%d", &FA[0][i++]);
str++;
while(isdigit(*str))
str++;
while(isspace(*str))
str++;
}
row = 1;
col = i;
while(!feof(fp))
{
FA = (int **) realloc(FA, sizeof(int *)*(row+1));
FA[row] = NULL;
fgets(temp, sizeof(char)*50, fp);
str = temp;
i= 0;
while(*str != '\0')
{
FA[row] = (int *)realloc(FA[row], sizeof(int)*(i+1));
sscanf(str, "%d", &FA[row][i++]);
str++;
while(isdigit(*str))
str++;
while(isspace(*str))
str++;
}
row++;
}
printf("Initial State: %d\n", init);
printf("Final states: ");
for(i = 0; i < fs; i++)
printf("%d ", FS[i]);
printf("\nInput Table:\n");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
printf("%d\t", FA[i][j]);
}
printf("\n");
}
while(1)
{
printf("Enter the string to be validated using the Finite Automata (\"q\" to quit): ");
scanf("%s", temp);
if(strcmp(temp, "q") == 0)
break;
str = temp;
r = 0;
while(*str != '\0')
{
c = tolower(*str) - 97;
if((c >= col) || (c < 0))
{
printf("%d", c);
printf("Invalid input symbol!\n");
c = -1;
break;
}
if(FA[r][c] != -1)
{
r = FA[r][c];
str++;
}
else
{
printf("Input symbol unexpected!\n");
c = -1;
break;
}
}
if(c == -1)
continue;
for(i = 0; i < fs; i++)
if(r == FS[i])
{
printf("String validated.\n");
break;
}
if(i == fs)
printf("String accepted(non-final state).\n");
};
return 0;
}
/* input.txt -
0
3
1 -1 -1
2 1 -1
-1 -1 3
-1 -1 -1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment