132 lines
2.7 KiB
C
132 lines
2.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define SIZE 256
|
|
|
|
typedef struct Tree {
|
|
char text[SIZE];
|
|
int isAnswer;
|
|
struct Tree *yes;
|
|
struct Tree *no;
|
|
} Tree;
|
|
|
|
// читання дерева
|
|
Tree* readTree() {
|
|
char line[SIZE];
|
|
|
|
if (fgets(line, SIZE, stdin) == NULL) return NULL;
|
|
|
|
// якщо пустий рядок → кінець бази
|
|
line[strcspn(line, "\r\n")] = 0;
|
|
if (line[0] == '\0') return NULL;
|
|
|
|
Tree *node = malloc(sizeof(Tree));
|
|
node->yes = NULL;
|
|
node->no = NULL;
|
|
|
|
line[strcspn(line, "\n")] = 0;
|
|
|
|
if (line[0] == '*') {
|
|
node->isAnswer = 1;
|
|
|
|
int i = 1;
|
|
while (line[i] == ' ') i++;
|
|
strcpy(node->text, line + i);
|
|
} else {
|
|
node->isAnswer = 0;
|
|
strcpy(node->text, line);
|
|
|
|
node->yes = readTree(); // a
|
|
node->no = readTree(); // n
|
|
}
|
|
|
|
return node;
|
|
}
|
|
|
|
// перевірка що після дерева є пустий рядок
|
|
int EmptyLine() {
|
|
char line[SIZE];
|
|
|
|
if (fgets(line, SIZE, stdin) == NULL) return 0;
|
|
|
|
if (strcmp(line, "\n") == 0) return 1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
// рахуємо відповіді (листи)
|
|
int Leaves(Tree *node) {
|
|
if (node == NULL) return 0;
|
|
|
|
if (node->isAnswer) return 1;
|
|
|
|
return Leaves(node->yes) + Leaves(node->no);
|
|
}
|
|
|
|
// звільнення памʼяті
|
|
void freeTree(Tree *node) {
|
|
if (node == NULL) return;
|
|
|
|
freeTree(node->yes);
|
|
freeTree(node->no);
|
|
free(node);
|
|
}
|
|
|
|
// запуск системи
|
|
void start(Tree *node) {
|
|
char input[10];
|
|
|
|
while (node != NULL) {
|
|
if (node->isAnswer) {
|
|
printf("* %s\n", node->text);
|
|
printf("Koniec\n");
|
|
return;
|
|
}
|
|
|
|
printf("%s\n", node->text);
|
|
|
|
if (fgets(input, 10, stdin) == NULL) {
|
|
printf("Koniec\n");
|
|
return;
|
|
}
|
|
|
|
if (input[0] == 'a') {
|
|
node = node->yes;
|
|
} else if (input[0] == 'n') {
|
|
node = node->no;
|
|
} else {
|
|
printf("Nerozumiem\n");
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
printf("Expert z bufetu to vie.\n");
|
|
|
|
Tree *root = readTree();
|
|
|
|
// перевірка чи дерево існує
|
|
if (root == NULL) {
|
|
printf("Chyba nacitania\n");
|
|
return 0;
|
|
}
|
|
|
|
// перевірка пустого рядка після бази
|
|
if (!EmptyLine()) {
|
|
printf("Chyba nacitania\n");
|
|
freeTree(root);
|
|
return 0;
|
|
}
|
|
|
|
int count = Leaves(root);
|
|
|
|
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
|
|
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
|
|
|
|
start(root);
|
|
|
|
freeTree(root);
|
|
return 0;
|
|
} |