usaa21/cv8/program.c

122 lines
2.4 KiB
C
Raw Permalink Normal View History

2021-11-24 22:55:34 +00:00
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
2021-11-25 15:20:34 +00:00
#define LINESIZE 50
2021-11-24 22:55:34 +00:00
struct tree{
2021-11-25 15:20:34 +00:00
char question[LINESIZE];
2021-11-24 22:55:34 +00:00
struct tree* left;
struct tree* right;
};
struct tree* read_tree();
void system_execute(struct tree* root);
int get_input(char *string);
int type_count(struct tree* root);
void destroy_tree(struct tree* root);
int main(){
struct tree* root = NULL;
root = read_tree();
2021-11-25 15:20:34 +00:00
char resp[LINESIZE];
memset(resp,0,LINESIZE);
2021-11-24 22:55:34 +00:00
get_input(resp);
if(strlen(resp)>1){
2021-11-25 10:00:37 +00:00
printf("Expert z bufetu to vie.\n");
2021-11-24 22:55:34 +00:00
puts("Chybna databaza");
exit(0);
}
puts("Expert z bufetu to vie.");
printf("Pozna %d druhov ovocia a zeleniny.\n",type_count(root));
2021-11-25 09:55:51 +00:00
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
2021-11-24 22:55:34 +00:00
system_execute(root);
getchar();
2021-11-25 09:58:00 +00:00
printf("Koniec\n");
2021-11-24 22:55:34 +00:00
destroy_tree(root);
return 0;
}
struct tree* read_tree(){
2021-11-25 15:20:34 +00:00
char buffer[LINESIZE];
memset(buffer,0,LINESIZE);
2021-11-24 22:55:34 +00:00
int flag = get_input(buffer);
if(flag==-1){
2021-11-25 10:00:37 +00:00
printf("Expert z bufetu to vie.\n");
2021-11-24 22:55:34 +00:00
puts("Chybna databaza");
exit(0);
}
struct tree* node = calloc(1,sizeof(struct tree));
2021-11-25 15:20:34 +00:00
memcpy(node->question,buffer,LINESIZE);
2021-11-24 22:55:34 +00:00
if(node->question[0]!='*'){
node->left = read_tree();
node->right = read_tree();
}
return node;
}
int get_input(char *string){
2021-11-25 15:20:34 +00:00
char* r = fgets(string,LINESIZE,stdin);
2021-11-24 22:55:34 +00:00
if(r==NULL){
2021-11-25 10:06:41 +00:00
return -1;
2021-11-24 22:55:34 +00:00
}
string[strlen(string)-1]='\0';
return 1;
}
void system_execute(struct tree* root){
if(root==NULL){
return;
}
printf("%s\n",root->question);
if(root->question[0]=='*'){
return;
}
2021-11-25 15:20:34 +00:00
char *resp = calloc(LINESIZE,sizeof(char));
2021-11-24 22:55:34 +00:00
int flag = get_input(resp);
if(flag==-1){
puts("Koniec vstupu");
exit(0);
}
if(resp[0]=='a'){
system_execute(root->left);
}else if(resp[0]=='n'){
system_execute(root->right);
}else{
puts("Nerozumiem");
exit(0);
}
}
int type_count(struct tree* root){
if(root==NULL){
return 0;
}
if(root->question[0]=='*'){
return 1;
}
int count= type_count(root->left)+type_count(root->right);
return count;
}
void destroy_tree(struct tree* root){
if (root == NULL){
return;
}
destroy_tree(root->left);
destroy_tree(root->right);
free(root);
}