Esempio n. 1
0
 /// <summary>
 /// Build a tree which represents an expression, which has the specified
 /// number of operandsand evaluates to the specified value.
 /// </summary>
 /// <param name="desiredValue">The value of the final expression when evaluated</param>
 /// <param name="numberOfOperands">The number of operands in the final expression</param>
 public Tree(int desiredValue, int numberOfOperands = 2)
 {
     if (operators == null)
     {
         operators = new List <char>();
         var allowed = Configuration.AllowedOperators;
         if (allowed.HasFlag(Configuration.Operators.ADD))
         {
             operators.Add('+');
         }
         if (allowed.HasFlag(Configuration.Operators.SUB))
         {
             operators.Add('-');
         }
         if (allowed.HasFlag(Configuration.Operators.MUL))
         {
             operators.Add('*');
         }
         if (allowed.HasFlag(Configuration.Operators.DIV))
         {
             operators.Add('/');
         }
     }
     Root = new OperandNode(desiredValue);
     if (numberOfOperands > 1)
     {
         Root = Root.Expand(numberOfOperands);
     }
 }
        /// <summary>
        /// Instantiate a new operator node and make sure that its value is as specified
        /// and the tree rooted at this node has the specified number of operand nodes.
        /// </summary>
        /// <param name="goal"></param>
        /// <param name="numberOfNewNodes"></param>
        public OperatorNode(int goal, int numberOfNewNodes = 2)
        {
            int  left, right;
            char op;

            // Choose a random valid operator for this node and split the goal
            do
            {
                op = Tree.operators.GetRandomElement();
            } while (!SplitHelper.SplitValue(goal, op, out left, out right));

            Operator = new Operator(op);
            Left     = new OperandNode(left);
            Right    = new OperandNode(right);

            int toLeft, toRight;

            // Distribute the number of new operands to be made between the two sides
            SplitHelper.SplitNumberOfOperands(left, right, numberOfNewNodes, out toLeft, out toRight);

            Left  = Left.Expand(toLeft);
            Right = Right.Expand(toRight);
        }
Esempio n. 3
0
 /// <summary>
 /// Instantiate an empty tree (used for creating trees after a format)
 /// </summary>
 public Tree()
 {
     Root = new OperandNode();
 }