Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DataStructures
- {
- class Program
- {
- static int Evaluate(string expression)
- {
- Stack<int> nums = new Stack<int>();
- Stack<char> operations = new Stack<char>();
- foreach (var item in expression)
- {
- if (char.IsDigit(item))
- {
- nums.Push(item - '0');
- }
- else if (item == '(')
- {
- nums.Push('(');
- }
- else if (item == '+' || item == '*')
- {
- operations.Push(item);
- }
- else if (item == ')')
- {
- char op = operations.Pop();
- if (op == '+')
- {
- int result = 0;
- while (nums.Peek() != '(')
- {
- result += nums.Pop();
- }
- nums.Pop(); // remove '('
- nums.Push(result);
- }
- else if (op == '*')
- {
- int result = 1;
- while (nums.Peek() != '(')
- {
- result *= nums.Pop();
- }
- nums.Pop(); // remove '('
- nums.Push(result);
- }
- }
- }
- return nums.Peek();
- }
- static int f(int x)
- {
- return 5 * x + 1;
- }
- static int m(int x, int y)
- {
- return (x < y) ? x : y;
- }
- static int s(int x, int y)
- {
- return x - y;
- }
- static int EvalFunction(string expression)
- {
- Stack<int> nums = new Stack<int>();
- Stack<char> func = new Stack<char>();
- foreach (var item in expression)
- {
- if (char.IsDigit(item))
- {
- nums.Push(item - '0');
- }
- else if (item == 'f' || item == 'm' || item == 's')
- {
- func.Push(item);
- }
- else if (item == ')')
- {
- int function = func.Pop();
- if (function == 'f')
- {
- int x = nums.Pop();
- nums.Push(f(x));
- }
- else if (function == 'm')
- {
- int y = nums.Pop();
- int x = nums.Pop();
- nums.Push(m(x, y));
- }
- else if (function == 's')
- {
- int y = nums.Pop();
- int x = nums.Pop();
- nums.Push(s(x, y));
- }
- }
- }
- return nums.Peek();
- }
- static void Main(string[] args)
- {
- Console.Write("Enter expression: ");
- string expr = Console.ReadLine();
- Console.WriteLine("{0} = {1}", expr, EvalFunction(expr));
- }
- }
- }
Add Comment
Please, Sign In to add comment