usaa24/cv7/program.c

99 lines
2.2 KiB
C
Raw Normal View History

2024-11-11 13:45:35 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
2024-11-13 22:44:04 +00:00
char text[100];
struct Node* yes;
struct Node* no;
2024-11-11 13:45:35 +00:00
} Node;
2024-11-13 22:44:04 +00:00
// Function to create a new node
Node* createNode(char* text) {
Node* node = (Node*)malloc(sizeof(Node));
strcpy(node->text, text);
node->yes = NULL;
node->no = NULL;
return node;
2024-11-11 13:45:35 +00:00
}
2024-11-13 22:44:04 +00:00
// Recursive function to read and build the tree
Node* readTree(FILE* file, int* count) {
char line[100];
2024-11-11 13:45:35 +00:00
2024-11-13 22:44:04 +00:00
if (!fgets(line, sizeof(line), file) || strcmp(line, "\n") == 0) {
return NULL;
2024-11-11 13:45:35 +00:00
}
2024-11-13 22:44:04 +00:00
// 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
2024-11-11 13:45:35 +00:00
}
2024-11-13 22:44:04 +00:00
// If it's a question, create a node and recursively read its children
Node* node = createNode(line);
node->yes = readTree(file, count);
node->no = readTree(file, count);
return node;
2024-11-11 13:45:35 +00:00
}
2024-11-13 22:44:04 +00:00
// Function to interact with the user and navigate the tree
void queryUser(Node* node) {
if (node == NULL) return;
2024-11-11 13:45:35 +00:00
if (node->yes == NULL && node->no == NULL) {
2024-11-13 22:44:04 +00:00
printf("Expert z bufetu to vie. Je to: %s\n", node->text);
2024-11-11 13:45:35 +00:00
return;
}
2024-11-13 22:44:04 +00:00
// 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;
scanf(" %c", &answer);
if (answer == 'a') {
queryUser(node->yes);
} else if (answer == 'n') {
queryUser(node->no);
} else {
printf("Nespravny vstup.\n");
2024-11-11 13:45:35 +00:00
}
}
2024-11-13 22:44:04 +00:00
// Function to free the tree
void freeTree(Node* node) {
if (node == NULL) return;
freeTree(node->yes);
freeTree(node->no);
free(node);
}
2024-11-13 21:28:02 +00:00
2024-11-11 13:45:35 +00:00
int main() {
2024-11-13 22:44:04 +00:00
FILE* file = fopen("baza.txt", "r");
if (!file) {
printf("Chyba pri nacitani suboru.\n");
return 1;
}
2024-11-11 13:45:35 +00:00
2024-11-13 22:44:04 +00:00
int count = 0;
Node* root = readTree(file, &count);
fclose(file);
2024-11-11 13:45:35 +00:00
2024-11-13 22:44:04 +00:00
if (root == NULL) {
printf("Chyba pri nacitani baze pravidiel.\n");
return 1;
2024-11-13 21:17:06 +00:00
}
2024-11-11 13:45:35 +00:00
2024-11-13 22:44:04 +00:00
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
queryUser(root);
freeTree(root);
return 0;
}