74 lines
1.7 KiB
C
Raw Normal View History

2024-02-09 13:20:39 -06:00
#include "lib/lib.h"
#include "lib/vec.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
DECL_VEC(CharVec, char);
CharVec readStdinToNewline() {
CharVec cvec = CharVec_new(2);
int ch;
while (EOF != (ch = fgetc(stdin)) && ch != '\n') {
CharVec_push(&cvec, ch);
}
return cvec;
}
bool pairedBraces(char open_brace, char close_brace) {
if (open_brace == '\0')
return true;
int asciiDiff = 2;
if (open_brace == '(' || open_brace == ')') {
asciiDiff = 1;
}
return ((int)open_brace - ((int)close_brace - asciiDiff)) == 0;
}
bool checkCharVecBalance(CharVec *cvec) {
int balance = 0;
CharVec braceStack = CharVec_new(cvec->elem_count);
char lastOpenBrace = '\0';
while (cvec->elem_count != 0) {
char val = CharVec_first(cvec);
switch (val) {
case '(':
case '[':
case '{':
CharVec_push(&braceStack, val);
balance++;
break;
case ')':
case ']':
case '}':
if (!pairedBraces(CharVec_pop(&braceStack), val))
return 0;
balance--;
break;
}
}
if (balance == 0) {
return -1;
} else {
return cvec->elem_count;
}
}
int main() {
print_header();
printf("Enter Expression: ");
CharVec cvec = readStdinToNewline();
char *input = malloc(cvec.elem_count + 1);
strcpy(input, cvec.data);
if (checkCharVecBalance(&cvec)) {
printf("It's balanced (^_^)\n");
return EXIT_SUCCESS;
} else {
printf("It's Not Balanced (0_0)\n");
return EXIT_FAILURE;
}
}