Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //A->ab|cd|ef no
- //A->ab|ac|d
- //A->aA'
- //A'->b|c
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #define MAX 100
- void longestCommonPrefix(char *result, char *str1, char *str2) {
- int i = 0;
- while (str1[i] && str2[i] && str1[i] == str2[i]) {
- result[i] = str1[i];
- i++;
- }
- result[i] = '\0';
- }
- void checkLeftFactoring(char nonTerminal, char *productions) {
- char commonPrefix[MAX] = "", remainingParts[MAX][MAX];
- int hasLeftFactoring = 0, partCount = 0;
- for (char *token = strtok(productions, "|"), *prev = NULL; token; token = strtok(NULL, "|")) {
- if (prev) {
- char tempPrefix[MAX];
- longestCommonPrefix(tempPrefix, prev, token);
- if (*tempPrefix) {
- hasLeftFactoring = 1;
- strcpy(commonPrefix, tempPrefix);
- strcpy(remainingParts[partCount++], prev + strlen(tempPrefix));
- strcpy(remainingParts[partCount++], token + strlen(tempPrefix));
- }
- }
- prev = token;
- }
- if (hasLeftFactoring) {
- printf("Left Factoring Grammar Detected.\n");
- printf("%c -> %s%c'\n", nonTerminal, commonPrefix, nonTerminal);
- printf("%c' -> ", nonTerminal);
- for (int i = 0; i < partCount; i++) {
- printf("%s%s", *remainingParts[i] ? remainingParts[i] : "e", (i < partCount - 1) ? " | " : "\n");
- }
- } else {
- printf("No Left Factoring detected.\n");
- }
- }
- int main() {
- char input[MAX];
- printf("Enter the production rule (e.g., A->ab|ac|d): ");
- fgets(input, MAX, stdin);
- input[strcspn(input, "\n")] = '\0';
- if (!isupper(input[0]) || strncmp(input + 1, "->", 2) != 0) {
- printf("Error: Invalid production rule format.\n");
- return 0;
- }
- checkLeftFactoring(input[0], input + 3);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement