usaa24/cv7/program.c

101 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char text[100];
struct Node* yes;
struct Node* no;
} Node;
// Function to create a new node
Node* createNode(char* text) {
Node* node = (Node*)malloc(sizeof(Node));
if (!node) {
fprintf(stderr, "Chyba pri alokacii pamate.\n");
exit(1);
}
strcpy(node->text, text);
node->yes = NULL;
node->no = NULL;
return node;
}
// Recursive function to read and build the tree
Node* readTree(int* count) {
char line[100];
if (!fgets(line, sizeof(line), stdin) || strcmp(line, "\n") == 0) {
return NULL;
}
// Remove newline character from line
line[strcspn(line, "\n")] = 0;
// Check if the line is an answer (starts with '*')
if (line[0] == '*') {
(*count)++;
return createNode(line + 1); // Skip the '*' character
}
// If it's a question, create a node and recursively read its children
Node* node = createNode(line);
node->yes = readTree(count);
node->no = readTree(count);
return node;
}
// Function to interact with the user and navigate the tree
void queryUser(Node* node) {
if (node == NULL) return;
if (node->yes == NULL && node->no == NULL) {
printf("Expert z bufetu to vie.\n");
printf("Je to: %s\n", node->text);
printf("Koniec\n");
return;
}
// Print question and get user's answer
printf("%s\n", node->text);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
char answer;
if (scanf(" %c", &answer) != 1) {
printf("Nespravny vstup.\n");
return;
}
if (answer == 'a') {
queryUser(node->yes);
} else if (answer == 'n') {
queryUser(node->no);
} else {
printf("Nespravny vstup.\n");
}
}
// Function to free the tree
void freeTree(Node* node) {
if (node == NULL) return;
freeTree(node->yes);
freeTree(node->no);
free(node);
}
int main() {
int count = 0;
Node* root = readTree(&count);
if (root == NULL) {
printf("Chyba pri nacitani baze pravidiel.\n");
return 1;
}
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
queryUser(root);
freeTree(root);
return 0;
}