usaa24/cv7/program.c

104 lines
2.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define SIZE 100
#define YES 'a'
#define NO 'n'
// Tree node structure
struct TreeNode {
char value[SIZE];
struct TreeNode* yes;
struct TreeNode* no;
};
// Function to create a new tree node
struct TreeNode* create_node(const char* text) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
strcpy(node->value, text);
node->yes = node->no = NULL;
return node;
}
// Recursive function to build the tree
struct TreeNode* read_tree() {
char buffer[SIZE];
if (!fgets(buffer, SIZE, stdin) || buffer[0] == '\n') return NULL;
// Remove newline character
buffer[strcspn(buffer, "\n")] = 0;
struct TreeNode* node = create_node(buffer);
// Check if it's a leaf node
if (buffer[0] != '*') {
node->yes = read_tree(); // Read 'yes' branch
node->no = read_tree(); // Read 'no' branch
}
return node;
}
// Count the leaf nodes (answers) in the tree
int count_leaf_nodes(struct TreeNode* node) {
if (node == NULL) return 0;
if (node->yes == NULL && node->no == NULL) return 1; // It's a leaf node
return count_leaf_nodes(node->yes) + count_leaf_nodes(node->no);
}
// Free memory allocated for the tree
void destroy_tree(struct TreeNode* node) {
if (node == NULL) return;
destroy_tree(node->yes);
destroy_tree(node->no);
free(node);
}
// Dialogue with user based on tree structure
void run_dialogue(struct TreeNode* node) {
if (!node) return;
printf("%s\n", node->value);
if (node->yes == NULL && node->no == NULL) {
printf("Expert z bufetu to vie.\n");
return;
}
char answer;
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
if (scanf(" %c", &answer) != 1 || (answer != YES && answer != NO)) {
printf("Odpovedajte 'a' alebo 'n'.\n");
return;
}
if (answer == YES) run_dialogue(node->yes);
else if (answer == NO) run_dialogue(node->no);
}
int main() {
// Read and build tree from input
struct TreeNode* root = read_tree();
// Check if rule base ended with an empty line
char check[SIZE];
if (!fgets(check, SIZE, stdin) || check[0] != '\n') {
printf("Neplatna baza pravidiel.\n");
destroy_tree(root);
return 1;
}
// Count leaf nodes
int count = count_leaf_nodes(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
// Run the dialogue system
run_dialogue(root);
// Free allocated memory
destroy_tree(root);
return 0;
}