Ejemplo n.º 1
0
        // This implements Interfaces which are stored in the "Code" folder referenced above
        static void UseInterfaces()
        {
            string add      = "+";
            string subtract = "-";
            string multiply = "*";
            string divide   = "/";

            var numOne = 2;
            var numTwo = 3;

            string userChoice = add;

            Dictionary <string, IMathOperator> strategies = new Dictionary <string, IMathOperator>()
            {
                { "+", new MathAdd() },
                { "-", new MathSubtract() },
                { "*", new MathMultiply() },
                { "/", new MathDivide() }
            };

            IMathOperator selectedStrategy = strategies[userChoice];
            int           result           = selectedStrategy.Operation(numOne, numTwo);

            Console.WriteLine(result);
        }
Ejemplo n.º 2
0
        private bool CHECK_IF_OPERATOR(string expression, ref int position, out IMathOperator @operator)
        {
            @operator = null;
            var currentChar = expression[position];
            var list        = SupportedOperators.Where(c => c.Keyword.StartsWith(currentChar.ToString()));

            if (list.Count() > 0)
            {
                var    start   = position;
                var    end     = start;
                string keyword = expression[start].ToString();
                if (keyword != "("
                    &&
                    keyword != ")")
                {
                    while (++end < expression.Length &&
                           (!char.IsDigit(expression[end]) && expression[end] != '(' && expression[end] != ')'))
                    {
                        keyword += expression[end];
                    }
                }
                var supportedOperator = (IMathOperator)SupportedOperators.FirstOrDefault(o => o.Keyword.StartsWith(keyword));

                @operator = supportedOperator;

                return(supportedOperator != null ? (position = start + @operator.Keyword.Length) > -1 : false);
            }
            return(false);
        }
Ejemplo n.º 3
0
        static void QueryUser()
        {
            Console.WriteLine("\nFirst Number:");
            var aVal = Console.ReadLine();

            Console.WriteLine("Math Operation? (+,-,/,*):");
            var strategy = Console.ReadLine();

            Console.WriteLine("Second Number:");
            var bVal = Console.ReadLine();

            if (int.TryParse(aVal, out var aNum) && int.TryParse(bVal, out var bNum))
            {
                IMathOperator selectedStrategy = strategies[strategy];

                var result = Calculate(aNum, bNum, selectedStrategy);

                Console.WriteLine($"Result: {result}\n");
            }

            Console.WriteLine("Would you like to conduct another math operation? (y/n):");
            var runAgain = Console.ReadLine();

            if (runAgain?.ToLower() == "y")
            {
                QueryUser();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Builds the statements that generate the value of this expression
        /// </summary>
        /// <param name="block">Block to which to add the statements</param>
        /// <param name="expr">Expression to build</param>
        /// <param name="operand1">First operand</param>
        /// <param name="operand2">second operand</param>
        /// <returns></returns>
        public static Declaration BuildStatements(Block block, Expression expr, Token operand1, Token operand2)
        {
            Token opToken = expr.Tokens[0];

            var            decl          = block.CreateTempDeclaration(TypeHelper.GetType(block, operand1));
            ValueStatement initialAssign = AssignmentHelper.ParseSingle(block, decl, operand1);

            block.Statements.Add(initialAssign);

            var asm = System.Reflection.Assembly.GetExecutingAssembly();

            foreach (var type in asm.GetTypes())
            {
                if (type.BaseType == typeof(MathStatement))
                {
                    try
                    {
                        IMathOperator mathOp = (IMathOperator)asm.CreateInstance(type.FullName);
                        if (opToken.Equals(mathOp.GetHandledOperator()))
                        {
                            MathStatement mathStatement;
                            Datum         datum = Datum.Parse(block, operand2);
                            if (datum == null)
                            {
                                MessageSystem.Instance.ThrowNewError(MessageSystem.ErrorCode.UndeclaredVar);
                                return(null);
                            }

                            if (decl.Type.IndirectionLevels > 0)
                            {
                                Type derefType = decl.Type.Clone() as Type;
                                derefType.Dereference();

                                var offsetDecl = block.CreateTempDeclaration(new BuiltInType("int"));
                                block.Statements.Add(AssignmentHelper.ParseSingle(block, offsetDecl, operand2));
                                var  imm  = new Immediate(new Token(derefType.Size.ToString()));
                                Mult mult = new Mult(offsetDecl, imm);
                                block.Statements.Add(mult);
                                datum = offsetDecl;
                            }

                            mathStatement = Activator.CreateInstance(type,
                                                                     new object[] { decl, datum }) as MathStatement;
                            block.Statements.Add(mathStatement);
                            break;
                        }
                    }
                    catch (MissingMethodException) { }
                }
            }

            return(decl);
        }
Ejemplo n.º 5
0
        static void FancyDict(int numOne, int numTwo, string userChoice, double result)
        {
            // Even Better: Return functions to avoid expensive instantiating
            Dictionary <string, Func <IMathOperator> > strategies = new Dictionary <string, Func <IMathOperator> >()
            {
                { "+", () => new MathAdd() },
                { "-", () => new MathMinus() },
                { "*", () => new MathMultiply() },
                { "/", () => new MathDivide() }
            };

            IMathOperator selectedStrategy = strategies[userChoice]();

            result = selectedStrategy.Operation(numOne, numTwo);
            Console.WriteLine(result);
        }
Ejemplo n.º 6
0
        static void Dict(int numOne, int numTwo, string userChoice, double result)
        {
            // Better: Dictionary with interface
            Dictionary <string, IMathOperator> strategies = new Dictionary <string, IMathOperator>()
            {
                { "+", new MathAdd() },
                { "-", new MathMinus() },
                { "*", new MathMultiply() },
                { "/", new MathDivide() }
            };

            IMathOperator selectedStrategy = strategies[userChoice];

            result = selectedStrategy.Operation(numOne, numTwo);
            Console.WriteLine(result);
        }
Ejemplo n.º 7
0
        public double compute(string rpnMathExpression)
        {
            string[] rpnTokens = rpnMathExpression.Split(' ');

            IMathOperator mathOperation = null;

            foreach (var token in rpnTokens)
            {
                if (isMathOperator(token))
                {
                    mathOperation = MathFactory.GetMathObjectByReflection(token);
                    extractInputs();
                    result = mathOperation.compute(firstNumber, secondNumber);
                    numberStack.Push(result);
                }
                else
                {
                    numberStack.Push(Convert.ToDouble(token));
                }
            }

            return(numberStack.Pop());
        }
Ejemplo n.º 8
0
        public static IMathOperator getMathObject(string mathOperation)
        {
            IMathOperator mathOperator = null;

            if (mathOperation.Equals("+"))
            {
                mathOperator = new Addition();
            }
            else if (mathOperation.Equals("-"))
            {
                mathOperator = new Subtraction();
            }
            else if (mathOperation.Equals("*"))
            {
                mathOperator = new Multiplication();
            }
            else if (mathOperation.Equals("/"))
            {
                mathOperator = new Division();
            }

            return(mathOperator);
        }
Ejemplo n.º 9
0
 static int Calculate(int a, int b, IMathOperator op)
 {
     return(op.Calculate(a, b));
 }
Ejemplo n.º 10
0
        public static IMathOperator GetMathObjectByReflection(string mathOperator)
        {
            IMathOperator mathOperation = (IMathOperator)Activator.CreateInstance(mathOperators[mathOperator]);

            return(mathOperation);
        }