usaa24/cv7/program.c

92 lines
1.9 KiB
C
Raw Permalink Normal View History

2024-11-11 13:40:23 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *text;
struct Node *yes;
struct Node *no;
} Node;
2024-11-11 13:40:57 +00:00
2024-11-11 13:40:23 +00:00
Node* create_node(const char *text) {
Node *node = (Node*) malloc(sizeof(Node));
node->text = strdup(text);
node->yes = NULL;
node->no = NULL;
return node;
}
2024-11-11 13:40:57 +00:00
2024-11-11 13:40:23 +00:00
Node* load_tree(int *item_count) {
char line[100];
if (!fgets(line, sizeof(line), stdin) || line[0] == '\n') {
return NULL;
}
2024-11-11 13:40:57 +00:00
line[strcspn(line, "\n")] = 0;
2024-11-11 13:40:23 +00:00
if (line[0] == '*') {
(*item_count)++;
2024-11-11 13:40:57 +00:00
return create_node(line + 1);
2024-11-11 13:40:23 +00:00
} else {
2024-11-11 13:40:57 +00:00
Node *node = create_node(line);
2024-11-11 13:40:23 +00:00
node->yes = load_tree(item_count);
node->no = load_tree(item_count);
return node;
}
}
2024-11-11 13:40:57 +00:00
2024-11-11 13:40:23 +00:00
void free_tree(Node *node) {
if (node) {
free(node->text);
free_tree(node->yes);
free_tree(node->no);
free(node);
}
}
2024-11-11 13:40:57 +00:00
2024-11-11 13:40:23 +00:00
void run_system(Node *node) {
while (node) {
if (node->yes == NULL && node->no == NULL) {
2024-11-11 13:46:40 +00:00
2024-11-11 13:47:52 +00:00
printf("*%s\n", node->text);
2024-11-11 13:40:23 +00:00
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 {
2024-11-11 13:49:27 +00:00
printf("Nerozumiem\n");
2024-11-11 13:40:23 +00:00
break;
}
}
}
int main() {
int item_count = 0;
2024-11-11 13:46:40 +00:00
printf("Expert z bufetu to vie.\n");
2024-11-11 13:40:23 +00:00
Node *root = load_tree(&item_count);
if (root == NULL) {
2024-11-11 13:40:57 +00:00
printf("Chba: bázu znalostí sa nepodarilo načítať.\n");
2024-11-11 13:40:23 +00:00
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;
}