usaa24/cv7/program.c

96 lines
2.3 KiB
C
Raw Permalink 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);
}
int ask_question(Node *node) {
if (node == NULL) return 1;
if (node->text[0] == '*') {
printf("%s", node->text);
return 1;
}
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
printf("%s", node->text);
char answer;
if (scanf(" %c", &answer) != 1 || (answer != 'a' && answer != 'n')) {
printf("Nerozumiem\n");
return 0; // Завершаем программу при неверном вводе.
}
if (answer == 'a') {
return ask_question(node->yes);
} else if (answer == 'n') {
return ask_question(node->no);
}
return 1;
}
int main() {
Node *root = load_knowledge_base();
if (root == NULL) {
printf("Chyba pri nacitani bazy pravidiel.\n");
printf("Koniec vstupu\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);
if (!ask_question(root)) {
free_tree(root);
return 0; // Завершаем программу при неверном вводе.
}
printf("Koniec\n"); // Завершаем с этим сообщением при успешном завершении
free_tree(root);
return 0;
}