Update a1/program.c

This commit is contained in:
Viktor Daniv 2024-10-26 19:31:08 +00:00
parent fbe547c8bc
commit 14fe6bb5c0

View File

@ -1,60 +1,68 @@
#include <stdio.h>
#include <string.h>
#define MAX 100
void serch_zatv(char vhod[MAX]) {
char first[2] = "{}";
char second[2] = "[]";
char third[2] = "<>";
char fourth[2] = "()";
int idx = 0;
int idt = 0;
char find[50] = {0};
// Pomocná funkcia na kontrolu páru zátvoriek
int is_matching_pair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']') ||
(open == '<' && close == '>');
}
// Funkcia na kontrolu správnosti zátvoriek
void check_brackets(const char *code) {
char stack[MAX];
int stack_top = -1; // vrchol zásobníka
while (vhod[idx] != '\0') {
if (vhod[idx] == first[0]) {
find[idt] = first[1];
idt++;
} else if (vhod[idx] == second[0]) {
find[idt] = second[1];
idt++;
} else if (vhod[idx] == third[0]) {
find[idt] = third[1];
idt++;
} else if (vhod[idx] == fourth[0]) {
find[idt] = fourth[1];
idt++;
} else {
for (int i = 0; i < idt; i++) {
if (vhod[idx] == find[i]) {
find[i] = '.';
for (int r = i + 1; r < idt; r++) {
if (find[r] != '.' && find[r] != '\0') {
printf("Crossed bracket %c at position %d, expected %c\n", vhod[idx], idx, find[i]);
return;
}
}
break;
}
printf("Read: %s\n", code);
for (int i = 0; code[i] != '\0'; i++) {
char c = code[i];
// Ak je znak otváracia zátvorka, pridaj ho na zásobník
if (c == '(' || c == '{' || c == '[' || c == '<') {
if (stack_top >= MAX - 1) {
printf("Stack overflow at position %d\n", i);
return;
}
stack[++stack_top] = c;
}
// Ak je znak zatváracia zátvorka
else if (c == ')' || c == '}' || c == ']' || c == '>') {
if (stack_top < 0) {
printf("Unexpected closing bracket %c at position %d\n", c, i);
return;
}
char top = stack[stack_top--];
if (!is_matching_pair(top, c)) {
printf("Crossed bracket %c in %d, expected %c\n", c, i, top);
return;
}
}
idx++;
}
for (int i = 0; i < idt; i++) {
if (find[i] != '.' && find[i] != '\0') {
printf("Unmatched bracket\n");
return;
}
// Skontroluj, či sú všetky zátvorky uzavreté
if (stack_top >= 0) {
printf("Unmatched bracket at the end\n");
} else {
printf("All brackets OK\n");
}
printf("Read: %s\nAll brackets OK\n", vhod);
}
int main() {
char riadok[MAX];
scanf("%s", riadok); // Без амперсанда &
serch_zatv(riadok);
char code[MAX];
// Načítaj vstup
printf("Enter code: ");
fgets(code, MAX, stdin);
// Odstráň novoriadok na konci
code[strcspn(code, "\n")] = '\0';
// Skontroluj zátvorky
check_brackets(code);
return 0;
}
}