private string BuildInfix(bool tokenize) { int i = 0; var s = new Stack <BuildInfixNode>(); var open = new BuildInfixNode("("); var close = new BuildInfixNode(")"); while (i < TokenizedPostfix.Length) { char c = TokenizedPostfix[i++]; if (c == '{') { if (TokenizedPostfix[i] == 'A') { int j = i + 3; // parsing an argument, j points at the 1st digit of the argument's index int k = j + 1; while (TokenizedPostfix[k] != '}') { ++k; } if (tokenize) { s.Push(new BuildInfixNode(TokenizedPostfix.Substring(i - 1, k - i + 2))); } else { s.Push(new BuildInfixNode(_argBook[int.Parse(TokenizedPostfix.Substring(j, k - j))])); } i = k + 1; } else { int j = i + 1; // parsing a const number, j points at the number's 1st digit while (TokenizedPostfix[j] != '}') { ++j; } if (tokenize) { s.Push(new BuildInfixNode(TokenizedPostfix.Substring(i - 1, j - i + 2))); } else { s.Push(new BuildInfixNode(TokenizedPostfix.Substring(i, j - i))); } i = j + 1; } } else if (c == 'N') { s.Push(new BuildInfixNode("-", s.Pop())); } else if (c == 'P') { s.Push(new BuildInfixNode("+", s.Pop())); } else { var x1 = s.Pop(); // merges a binary operator with two of its operands var x2 = s.Pop(); s.Push(new BuildInfixNode(open, x2, c.ToString(), x1, close)); } } return(s.Pop().ToString()); }
public decimal Compute(params decimal[] args) { if (args.Length != ArgCount) { throw new ArgumentException("Incorrect argument count."); } int i = 0; var s = new Stack <decimal>(); while (i < TokenizedPostfix.Length) { char c = TokenizedPostfix[i++]; if (c == '{') { if (TokenizedPostfix[i] == 'A') { int index = TokenizedPostfix[i += 3] - '0'; ++i; while (TokenizedPostfix[i] != '}') { index *= 10; index += TokenizedPostfix[i++] - '0'; } s.Push(args[index]); ++i; } else { int j = i + 1; while (TokenizedPostfix[j] != '}') { ++j; } s.Push(decimal.Parse(TokenizedPostfix.Substring(i, j - i))); i = j + 1; } } else if (c == 'N') { s.Push(-s.Pop()); } else if (c == 'P') { s.Push(Math.Abs(s.Pop())); } else { var x1 = s.Pop(); var x2 = s.Pop(); if (c == '+') { s.Push(x2 + x1); } else if (c == '-') { s.Push(x2 - x1); } else if (c == '*') { s.Push(x2 * x1); } else if (c == '/') { if (x1 == 0) { throw new ArithmeticException("Division by zero."); } s.Push(x2 / x1); } else if (c == '^') { if (x2 < 0 && ((x1 > 0 && x1 < 1) || (x1 > -1 && x1 < 0))) { throw new ArithmeticException("Incorrect exponentation: " + x2.ToString() + "^" + x1.ToString() + "."); } s.Push((decimal)Math.Pow((double)x2, (double)x1)); } else if (c == '%') { if (x1 == 0) { throw new ArithmeticException("Division by zero."); } s.Push(x2 % x1); } } } return(s.Pop()); }