usaa24/cv7/program.c
2024-11-11 14:40:57 +01:00

92 lines
2.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *text;
struct Node *yes;
struct Node *no;
} Node;
Node* create_node(const char *text) {
Node *node = (Node*) malloc(sizeof(Node));
node->text = strdup(text);
node->yes = NULL;
node->no = NULL;
return node;
}
Node* load_tree(int *item_count) {
char line[100];
if (!fgets(line, sizeof(line), stdin) || line[0] == '\n') {
return NULL;
}
line[strcspn(line, "\n")] = 0;
if (line[0] == '*') {
(*item_count)++;
return create_node(line + 1);
} else {
Node *node = create_node(line);
node->yes = load_tree(item_count);
node->no = load_tree(item_count);
return node;
}
}
void free_tree(Node *node) {
if (node) {
free(node->text);
free_tree(node->yes);
free_tree(node->no);
free(node);
}
}
void run_system(Node *node) {
while (node) {
if (node->yes == NULL && node->no == NULL) {
printf("Expert z bufetu to vie.\n");
printf("* %s\n", node->text);
printf("Koniec\n");
break;
}
printf("%s\n", node->text);
char answer;
scanf(" %c", &answer);
if (answer == 'a') {
node = node->yes;
} else if (answer == 'n') {
node = node->no;
} else {
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
break;
}
}
}
int main() {
int item_count = 0;
printf("Načítajte bázu znalostí:\n");
Node *root = load_tree(&item_count);
if (root == NULL) {
printf("Chba: bázu znalostí sa nepodarilo načítať.\n");
return 1;
}
printf("Pozna %d druhov ovocia a zeleniny.\n", item_count);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
run_system(root);
free_tree(root);
return 0;
}