usaa24/cv7/program.c

97 lines
2.3 KiB
C
Raw Normal View History

2024-11-06 08:44:29 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 100
typedef struct Node {
char text[MAX_LINE_LENGTH];
struct Node *yes;
struct Node *no;
} Node;
Node* create_node(const char* text) {
Node *node = (Node*)malloc(sizeof(Node));
if (!node) {
2024-11-06 08:53:54 +00:00
fprintf(stderr, "Memory allocation error.\n");
2024-11-06 08:44:29 +00:00
exit(1);
}
strncpy(node->text, text, MAX_LINE_LENGTH);
node->yes = NULL;
node->no = NULL;
return node;
}
Node* parse_knowledge_base(FILE *file) {
char line[MAX_LINE_LENGTH];
if (!fgets(line, sizeof(line), file)) {
return NULL;
}
line[strcspn(line, "\n")] = 0;
if (line[0] == '*') {
2024-11-06 08:53:54 +00:00
return create_node(line + 1);
2024-11-06 08:44:29 +00:00
} else {
Node *node = create_node(line);
node->yes = parse_knowledge_base(file);
node->no = parse_knowledge_base(file);
return node;
}
}
int count_products(Node *node) {
if (!node) return 0;
2024-11-06 08:53:54 +00:00
if (!node->yes && !node->no) return 1;
2024-11-06 08:44:29 +00:00
return count_products(node->yes) + count_products(node->no);
}
void run_expert_system(Node *node) {
while (node) {
2024-11-06 08:53:54 +00:00
if (!node->yes && !node->no) {
printf("The expert knows: %s.\n", node->text);
2024-11-06 08:44:29 +00:00
return;
}
printf("%s\n", node->text);
2024-11-06 08:53:54 +00:00
printf("Answer 'a' for the first option or 'n' for the second option: ");
2024-11-06 08:44:29 +00:00
char answer;
scanf(" %c", &answer);
if (answer == 'a') {
node = node->yes;
} else if (answer == 'n') {
node = node->no;
} else {
2024-11-06 08:53:54 +00:00
printf("Invalid answer. Exiting.\n");
2024-11-06 08:44:29 +00:00
return;
}
}
}
int main() {
2024-11-06 08:53:54 +00:00
printf("Attempting to open the knowledge base file...\n");
2024-11-06 08:44:29 +00:00
FILE *file = fopen("knowledge_base.txt", "r");
if (!file) {
2024-11-06 08:53:54 +00:00
perror("Failed to open the knowledge base file");
2024-11-06 08:44:29 +00:00
return 1;
}
2024-11-06 08:53:54 +00:00
printf("File successfully opened.\n");
2024-11-06 08:44:29 +00:00
Node *root = parse_knowledge_base(file);
fclose(file);
if (!root) {
2024-11-06 08:53:54 +00:00
printf("The knowledge base could not be loaded.\n");
2024-11-06 08:44:29 +00:00
return 1;
}
int product_count = count_products(root);
2024-11-06 08:53:54 +00:00
printf("The system knows about %d types of fruits and vegetables.\n", product_count);
2024-11-06 08:44:29 +00:00
run_expert_system(root);
free(root);
return 0;
}