-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrp.c
More file actions
75 lines (74 loc) · 2.49 KB
/
srp.c
File metadata and controls
75 lines (74 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <string.h>
struct ProductionRule
{
char left[10];
char right[10];
};
int main()
{
char input[20], stack[50], temp[50], ch[2], *token1, *token2, *substring;
int i, j, stack_length, substring_length, stack_top, rule_count = 0;
struct ProductionRule rules[10];
stack[0] = '\0';
printf("\nEnter the number of production rules: ");
scanf("%d", &rule_count);
printf("\nEnter the production rules (in the form 'left->right'): \n");
for (i = 0; i < rule_count; i++)
{
scanf("%s", temp);
token1 = strtok(temp, "->");
token2 = strtok(NULL, "->");
strcpy(rules[i].left, token1);
strcpy(rules[i].right, token2);
}
printf("\nEnter the input string: ");
scanf("%s", input);
i = 0;
while (1)
{
if (i < strlen(input))
{
ch[0] = input[i];
ch[1] = '\0';
i++;
strcat(stack, ch);
printf("%s\t", stack);
for (int k = i; k < strlen(input); k++)
{
printf("%c", input[k]);
}
printf("\tShift %s\n", ch);
}
for (j = 0; j < rule_count; j++)
{
substring = strstr(stack, rules[j].right);
if (substring != NULL)
{
stack_length = strlen(stack);
substring_length = strlen(substring);
stack_top = stack_length - substring_length;
stack[stack_top] = '\0';
strcat(stack, rules[j].left);
printf("%s\t", stack);
for (int k = i; k < strlen(input); k++)
{
printf("%c", input[k]);
}
printf("\tReduce %s->%s\n", rules[j].left, rules[j].right);
j = -1; // Restart the loop to ensure immediate reduction of the newly derived production rule
}
}
if (strcmp(stack, rules[0].left) == 0 && i == strlen(input))
{
printf("\nAccepted\n\n");
break;
}
if (i == strlen(input))
{
printf("\nNot Accepted");
break;
}
}
return 0;
}SRP