Advertisement
Sri27119

cd5 left factoring

Nov 20th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. //A->ab|cd|ef no
  2. //A->ab|ac|d
  3. //A->aA'
  4. //A'->b|c
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <ctype.h>
  9.  
  10. #define MAX 100
  11.  
  12. void longestCommonPrefix(char *result, char *str1, char *str2) {
  13. int i = 0;
  14. while (str1[i] && str2[i] && str1[i] == str2[i]) {
  15. result[i] = str1[i];
  16. i++;
  17. }
  18. result[i] = '\0';
  19. }
  20.  
  21. void checkLeftFactoring(char nonTerminal, char *productions) {
  22. char commonPrefix[MAX] = "", remainingParts[MAX][MAX];
  23. int hasLeftFactoring = 0, partCount = 0;
  24.  
  25. for (char *token = strtok(productions, "|"), *prev = NULL; token; token = strtok(NULL, "|")) {
  26. if (prev) {
  27. char tempPrefix[MAX];
  28. longestCommonPrefix(tempPrefix, prev, token);
  29. if (*tempPrefix) {
  30. hasLeftFactoring = 1;
  31. strcpy(commonPrefix, tempPrefix);
  32. strcpy(remainingParts[partCount++], prev + strlen(tempPrefix));
  33. strcpy(remainingParts[partCount++], token + strlen(tempPrefix));
  34. }
  35. }
  36. prev = token;
  37. }
  38.  
  39. if (hasLeftFactoring) {
  40. printf("Left Factoring Grammar Detected.\n");
  41. printf("%c -> %s%c'\n", nonTerminal, commonPrefix, nonTerminal);
  42. printf("%c' -> ", nonTerminal);
  43. for (int i = 0; i < partCount; i++) {
  44. printf("%s%s", *remainingParts[i] ? remainingParts[i] : "e", (i < partCount - 1) ? " | " : "\n");
  45. }
  46. } else {
  47. printf("No Left Factoring detected.\n");
  48. }
  49. }
  50.  
  51. int main() {
  52. char input[MAX];
  53.  
  54. printf("Enter the production rule (e.g., A->ab|ac|d): ");
  55. fgets(input, MAX, stdin);
  56. input[strcspn(input, "\n")] = '\0';
  57.  
  58. if (!isupper(input[0]) || strncmp(input + 1, "->", 2) != 0) {
  59. printf("Error: Invalid production rule format.\n");
  60. return 0;
  61. }
  62.  
  63. checkLeftFactoring(input[0], input + 3);
  64. return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement