This commit is contained in:
Denis Landa 2025-11-20 21:45:05 +01:00
parent c43329801b
commit 5bc6b97f31

View File

@ -2,93 +2,102 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define VELKOST 256 #define SIZE 256
struct Uzol{ struct tree {
char text[VELKOST]; char text[SIZE];
struct Uzol* ano; struct tree* yes;
struct Uzol* nie; struct tree* no;
}; };
struct Uzol* nacitaj_uzol(){ int count_items = 0;
char riadok[VELKOST];
if(!fgets(riadok, VELKOST, stdin)) struct tree* read_tree() {
char buffer[SIZE];
if (!fgets(buffer, SIZE, stdin))
return NULL; return NULL;
if(riadok[0] == '\n') if (buffer[0] == '\n')
return NULL; return NULL;
struct Uzol* u = malloc(sizeof(struct Uzol)); struct tree* node = malloc(sizeof(struct tree));
strcpy(u->text, riadok); strcpy(node->text, buffer);
u->ano = NULL; node->yes = NULL;
u->nie = NULL; node->no = NULL;
if(riadok[0] == '*'){ if (buffer[0] == '*') {
return u; count_items++;
return node;
} }
u->ano = nacitaj_uzol(); node->yes = read_tree();
u->nie = nacitaj_uzol(); if (!node->yes) {
return u; printf("Chyba\n");
exit(0);
} }
void zrus_strom(struct Uzol* u){ node->no = read_tree();
if(!u) return; if (!node->no) {
zrus_strom(u->ano); printf("Chyba\n");
zrus_strom(u->nie); exit(0);
free(u);
} }
int pocet_tovarov(struct Uzol* u){ return node;
if(!u) return 0;
if(u->text[0] == '*') return 1;
return pocet_tovarov(u->ano) + pocet_tovarov(u->nie);
} }
void spusti_system(struct Uzol* u){ void destroy_tree(struct tree* t) {
if(u->text[0] == '*'){ if (!t) return;
printf("%s", u->text); destroy_tree(t->yes);
destroy_tree(t->no);
free(t);
}
void run(struct tree* t) {
printf("%s", t->text);
if (t->text[0] == '*') {
printf("Koniec\n"); printf("Koniec\n");
return; return;
} }
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); printf("Odpovedajte 'a' alebo 'n'\n");
printf("%s", u->text);
char c; char c;
if (scanf(" %c", &c) != 1) { if (scanf(" %c", &c) != 1) {
printf("Koniec vstupu\n"); printf("Chyba\n");
return; return;
} }
if(c == 'a'){ if (c == 'a')
spusti_system(u->ano); run(t->yes);
} else if (c == 'n')
else if(c == 'n'){ run(t->no);
spusti_system(u->nie); else
} printf("Chyba\n");
else{
printf("Nerozumiem\n");
}
} }
int main() { int main() {
struct Uzol* koren = nacitaj_uzol(); struct tree* root = read_tree();
if(!koren){ if (!root) {
printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n"); printf("Chyba\n");
return 0; return 0;
} }
int pocet = pocet_tovarov(koren); char line[SIZE];
if (!fgets(line, SIZE, stdin) || line[0] != '\n') {
printf("Expert z bufetu to vie.\n"); printf("Chyba\n");
printf("Pozna %d druhov ovocia a zeleniny.\n", pocet); destroy_tree(root);
return 0;
spusti_system(koren); }
zrus_strom(koren);
printf("MUDrC to vie.\n");
printf("Pozna %d druhov ovocia a zeleniny.\n", count_items);
run(root);
destroy_tree(root);
return 0; return 0;
} }