Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdbool.h>
- #define NMAX 101
- #define SIGMA ('z' - 'a' + 1)
- int opPrec(char op) {
- if (strchr("+-", op)) {
- return 1;
- }
- if (strchr("*/", op)) {
- return 2;
- }
- return 0;//not op
- }
- char *toPostfix(const char infix[]) {
- const int n = strlen(infix);
- int top = -1;
- static char res[NMAX], st[NMAX];
- for (int i = 0; i < n; i++) {
- if (infix[i] == '(') {
- st[++top] = infix[i];
- } else if (infix[i] == ')') {
- while (top >= 0 && st[top] != '(') {
- strncat(res, &st[top--], 1);
- }
- top--;
- } else if (opPrec(infix[i])) {
- while (top >= 0 && opPrec(infix[i]) <= opPrec(st[top])) {
- strncat(res, &st[top--], 1);
- }
- st[++top] = infix[i];
- } else if (isalpha(infix[i])) {
- strncat(res, &infix[i], 1);
- }
- }
- while (top >= 0) {
- strncat(res, &st[top--], 1);
- }
- return res;
- }
- int computeOp(int a, int b, char op) {
- switch(op) {
- case '+':
- return a + b;
- case '-':
- return a - b;
- case '*':
- return a * b;
- case '/':
- return a / b;
- }
- return 0;//to supress warning
- }
- int evalPostfixEx(const char postfix[], const int valOf[SIGMA]) {
- static int st[NMAX];
- int top = -1;
- for (int i = 0; postfix[i]; i++) {
- if (isalpha(postfix[i])) {
- st[++top] = valOf[postfix[i] - 'a'];
- } else {
- int op2 = st[top--];
- int op1 = st[top--];
- int res = computeOp(op1, op2, postfix[i]);
- st[++top] = res;
- }
- }
- return st[top];
- }
- int cntLetters(const char s[]) {
- static bool used[SIGMA];
- for (int i = 0; s[i]; i++) {
- used[s[i] - 'a'] = true;
- }
- int cnt = 0;
- for (int let = 0; let < SIGMA; let++) {
- cnt += used[let];
- }
- return cnt;
- }
- int main(void) {
- static char infix[NMAX];
- static int valOf[SIGMA];
- if (!fgets(infix, NMAX, stdin)) {
- perror("");
- exit(-1);
- }
- int nrLetters = cntLetters(infix);
- for (int i = 0; i < nrLetters; i++) {
- scanf("%d", &valOf[i]);
- }
- char *postfix = toPostfix(infix);
- puts(postfix);
- printf("%d\n", evalPostfixEx(postfix, valOf));//*/
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement