usaa24/cv7/program.c

93 lines
2.0 KiB
C
Raw Normal View History

2024-11-14 20:29:44 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-11-14 20:44:07 +00:00
#define MAX_LENGTH 100
2024-11-14 20:29:44 +00:00
typedef struct Node {
2024-11-14 20:44:07 +00:00
char text[MAX_LENGTH];
2024-11-14 20:29:44 +00:00
struct Node *yes;
struct Node *no;
} Node;
2024-11-14 20:44:07 +00:00
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);
2024-11-14 20:29:44 +00:00
}
2024-11-14 20:44:07 +00:00
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();
2024-11-14 20:29:44 +00:00
}
2024-11-14 20:44:07 +00:00
return node;
2024-11-14 20:29:44 +00:00
}
2024-11-14 20:44:07 +00:00
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);
2024-11-14 20:29:44 +00:00
}
2024-11-14 20:44:07 +00:00
void ask_question(Node *node) {
if (node == NULL) return;
2024-11-15 03:54:22 +00:00
2024-11-14 20:44:07 +00:00
if (node->text[0] == '*') {
2024-11-14 20:48:28 +00:00
printf("Expert z bufetu to vie.\n");
2024-11-15 03:56:21 +00:00
printf("%s", node->text);
2024-11-14 20:44:07 +00:00
return;
}
2024-11-14 20:29:44 +00:00
2024-11-15 03:56:21 +00:00
printf("%s", node->text);
2024-11-14 20:44:07 +00:00
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
2024-11-14 20:48:28 +00:00
char answer;
2024-11-14 20:44:07 +00:00
if (scanf(" %c", &answer) != 1) {
printf("Neplatny vstup.\n");
return;
}
2024-11-14 20:29:44 +00:00
2024-11-14 20:44:07 +00:00
if (answer == 'a') {
ask_question(node->yes);
} else if (answer == 'n') {
ask_question(node->no);
} else {
printf("Neplatny vstup.\n");
2024-11-14 20:29:44 +00:00
}
}
2024-11-14 20:36:17 +00:00
int main() {
2024-11-14 20:44:07 +00:00
Node *root = load_knowledge_base();
2024-11-14 20:36:17 +00:00
2024-11-14 20:44:07 +00:00
if (root == NULL) {
printf("Chyba pri nacitani bazy pravidiel.\n");
return 1;
}
2024-11-14 20:36:17 +00:00
2024-11-14 20:44:07 +00:00
int item_count = count_items(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", item_count);
2024-11-14 20:29:44 +00:00
2024-11-14 20:44:07 +00:00
ask_question(root);
2024-11-14 20:48:28 +00:00
printf("Koniec\n"); // Завершаем программу после вопроса
2024-11-14 20:44:07 +00:00
free_tree(root);
2024-11-14 20:29:44 +00:00
return 0;
}