usaa24/cv7/program.c

93 lines
2.0 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 100
typedef struct Node {
char text[MAX_LENGTH];
struct Node *yes;
struct Node *no;
} Node;
Node* create_node(char *text) {
Node *new_node = (Node*)malloc(sizeof(Node));
strcpy(new_node->text, text);
new_node->yes = NULL;
new_node->no = NULL;
return new_node;
}
void free_tree(Node *node) {
if (node == NULL) return;
free_tree(node->yes);
free_tree(node->no);
free(node);
}
Node* load_knowledge_base() {
char line[MAX_LENGTH];
if (!fgets(line, MAX_LENGTH, stdin)) return NULL;
if (line[0] == '\n') return NULL;
Node *node = create_node(line);
if (line[0] != '*') {
node->yes = load_knowledge_base();
node->no = load_knowledge_base();
}
return node;
}
int count_items(Node *node) {
if (node == NULL) return 0;
if (node->text[0] == '*') return 1;
return count_items(node->yes) + count_items(node->no);
}
void ask_question(Node *node) {
if (node == NULL) return;
if (node->text[0] == '*') {
printf("%s", node->text);
return;
}
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
printf("%s", node->text);
char answer;
if (scanf(" %c", &answer) != 1) {
printf("Neplatny vstup.\n");
return;
}
if (answer == 'a') {
ask_question(node->yes);
} else if (answer == 'n') {
ask_question(node->no);
} else {
printf("Neplatny vstup.\n");
}
}
int main() {
Node *root = load_knowledge_base();
if (root == NULL) {
printf("Chyba pri nacitani bazy pravidiel.\n");
return 1;
}
printf("Expert z bufetu to vie.\n"); // Сообщение об успешной загрузке базы
int item_count = count_items(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", item_count);
ask_question(root);
printf("Koniec\n");
free_tree(root);
return 0;
}