88 lines
2.2 KiB
C
88 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define SIZE 1024
|
|
|
|
struct Node {
|
|
char value[SIZE];
|
|
struct Node* left;
|
|
struct Node* right;
|
|
};
|
|
|
|
void destroy_tree(struct Node* node) {
|
|
if (node == NULL) return;
|
|
destroy_tree(node->left);
|
|
destroy_tree(node->right);
|
|
free(node);
|
|
}
|
|
|
|
struct Node* read_tree(void) {
|
|
char buffer[SIZE] = {0};
|
|
char* r = fgets(buffer, SIZE, stdin);
|
|
if (r == NULL || buffer[0] == '\n' || buffer[0] == '\r') {
|
|
return NULL;
|
|
}
|
|
struct Node* node = calloc(1, sizeof(struct Node));
|
|
if (node == NULL) return NULL;
|
|
memcpy(node->value, buffer, SIZE);
|
|
|
|
if (buffer[0] != '*') {
|
|
node->left = read_tree();
|
|
if (node->left == NULL || node->right == NULL) {
|
|
destroy_tree(node);
|
|
return NULL;
|
|
}
|
|
}
|
|
return node;
|
|
}
|
|
|
|
int count_leaves(const struct Node* node) {
|
|
if (node == NULL) return 0;
|
|
if (node->left == NULL && node->right == NULL) return 1;
|
|
return count_leaves(node->left) + count_leaves(node->right);
|
|
}
|
|
|
|
void run_system(struct Node* node) {
|
|
if (node == NULL) return;
|
|
printf("%s", node->value);
|
|
|
|
if (node->left == NULL && node->right == NULL) {
|
|
printf("End\n");
|
|
return;
|
|
}
|
|
char answer[SIZE];
|
|
if (fgets(answer, SIZE, stdin) == NULL) return;
|
|
answer[strcspn(answer, "\r\n")] = '\0';
|
|
|
|
if (strcmp(answer, "a") == 0) {
|
|
run_system(node->left);
|
|
} else if (strcmp(answer, "n") == 0) {
|
|
run_system(node->right);
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
|
|
int main(void) {
|
|
struct Node* root = read_tree();
|
|
if (root == NULL) {
|
|
printf("Error: failed to load the rule base.\n");
|
|
return 1;
|
|
}
|
|
char sep[SIZE];
|
|
if (fgets(sep, SIZE, stdin) == NULL || (sep[0] != '\n' && sep[0] != '\r')) {
|
|
printf("Error: missing blank separator line.\n");
|
|
destroy_tree(root);
|
|
return 1;
|
|
}
|
|
int leaves = count_leaves(root);
|
|
printf("Expert z bufetu to vie.\n");
|
|
printf("Pozna %d druhov ovocia a zeleniny.\n", leaves);
|
|
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
|
|
|
|
run_system(root);
|
|
destroy_tree(root);
|
|
|
|
return 0;
|
|
} |