diff --git a/a1/main b/a1/main new file mode 100755 index 0000000..5bc851c Binary files /dev/null and b/a1/main differ diff --git a/a1/program.c b/a1/program.c index 53c5fdf..bd9dc62 100644 --- a/a1/program.c +++ b/a1/program.c @@ -1 +1,72 @@ #include +#include + +#define MAX_LEN 101 + +typedef struct { + char bracket; + int position; +} StackItem; + +int is_opening(char ch) { + return ch == '(' || ch == '{' || ch == '[' || ch == '<'; +} + +int is_closing(char ch) { + return ch == ')' || ch == '}' || ch == ']' || ch == '>'; +} + +char matching_bracket(char ch) { + switch (ch) { + case ')': return '('; + case '}': return '{'; + case ']': return '['; + case '>': return '<'; + default: return 0; + } +} + +void check_brackets(const char *line) { + StackItem stack[MAX_LEN]; + int stack_top = -1; + + printf("Read: %s\n", line); + + for (int i = 0; line[i] != '\0'; i++) { + char ch = line[i]; + + if (is_opening(ch)) { + if (stack_top < MAX_LEN - 1) { + stack[++stack_top].bracket = ch; + stack[stack_top].position = i; + } else { + printf("Error: Stack overflow\n"); + return; + } + } else if (is_closing(ch)) { + if (stack_top >= 0 && stack[stack_top].bracket == matching_bracket(ch)) { + stack_top--; + } else { + printf("Crossed bracket %c in %d, expected %c\n", ch, i, + stack_top >= 0 ? matching_bracket(stack[stack_top].bracket) : '#'); + return; + } + } + } + + if (stack_top >= 0) { + printf("Unmatched bracket %c in %d\n", stack[stack_top].bracket, stack[stack_top].position); + } else { + printf("All brackets OK\n"); + } +} + +int main() { + char line[MAX_LEN]; + if (fgets(line, sizeof(line), stdin)) { + line[strcspn(line, "\n")] = '\0'; + check_brackets(line); + } + return 0; +} +