Exemplo n.º 1
0
        public void AddBinary(ExpressionType nodeType)
        {
            if (Current != null)
                _stack.Push( Current );

            Current = new BinaryNode( nodeType );
        }
Exemplo n.º 2
0
        public static void CreateTree()
        {
            m_Tree = new BinaryNode();
            int nrBits = 0, val = 0;
            BinaryNode current = m_Tree;

            for(int i = 0; i < 257; i++) // was 257
            {
            current = m_Tree;
            nrBits = (int)bit_table[i,0] - 1;
            val = (int)bit_table[i,1];

            for(int n = nrBits; n >= 0; n--)
            {
                if((val >> n) % 2 == 1)
                {
                    if(current.Left == null)
                            current.Left = new BinaryNode();
                    current = current.Left;
                }
                else
                {
                    if(current.Right == null)
                            current.Right = new BinaryNode();
                    current = current.Right;
                }
            }

            current.IsLeaf = true;
            current.Value = i;
            }
        }
Exemplo n.º 3
0
 private void _addChildrenAvoidEndpoinDoubleAdding(ref Stack<BinaryNode> traverseStack, BinaryNode node)
 {
     if (node.RightChild != null) traverseStack.Push(node.RightChild);
     if (node.LeftChild != null)
     {
         if (node.LeftChild.Type != NodeType.ConditionEndPoint) traverseStack.Push(node.LeftChild);
         if (_conditionEndPointRightBranchChild(node)) traverseStack.Push(node.LeftChild);
     }
 }
Exemplo n.º 4
0
        public void CompleteBinary( )
        {
            if (!_stack.Any())
                return;

            BinaryNode node = _stack.Pop();
            if (node.Left == null)
                node.Left = Current;
            else
                node.Right = Current;

            Current = node;
        }
        static BinaryNode<int> GetSampleTree()
        {
            int[] content = { 5, 3, 7, 2, 4, 6, 8 };

            BinaryNode<int> root = new BinaryNode<int>(content[0]);

            for (int i = 1; i < content.Length; i++)
            {
                root.Add(content[i]);
            }

            return root;
        }
Exemplo n.º 6
0
 public BinaryNode(int[,] value, int row, int col)
 {
     var maxRow = value.GetUpperBound(0);
     var maxCol = value.GetUpperBound(1);
     Value = value[row, col];
     if(row + 1 <= maxRow)
     {
         Left = new BinaryNode(value, row +1, col);
         if(col +1 <= maxCol)
         {
             Right = new BinaryNode(value, row + 1, col + 1);
         }
     }
 }
Exemplo n.º 7
0
        public void Execute(TypeModel model, string caption)
        {
            BinaryNode head = new BinaryNode();
            BinaryNode node = head;
            // 13 is the magic limit that triggers recursion check        
            for (int i = 0; i < 13; ++i)
            {
                node.Left = new BinaryNode();
                node = (BinaryNode)node.Left;
            }

            var clone = (Node)model.DeepClone(head);
            Assert.AreEqual(head.Count(), clone.Count(), caption);
        }
        /// <summary>
        /// Create a balanced binary search tree with n nodes
        /// </summary>
        static BinaryNode<int> GetBalancedTree(int n)
        {
            List<int> list = new List<int>(n);
            for (int i = 1; i <= n; i++) list.Add(i);

            List<int> balancedList = GetBalancedList(list);

            BinaryNode<int> root = new BinaryNode<int>(balancedList[0]);
            for (int i = 1; i < balancedList.Count; i++)
            {
                root.Add(balancedList[i]);
            }

            return root;
        }
        public void AddNode_AddEightRandomNumbers_OrderIsSorted()
        {
            BinaryNode<int> root = new BinaryNode<int>(4);
            List<int> expected = new List<int>() { 4 };
            Random rand = new Random();

            for (int i = 0; i < 8; i++)
            {
                int x = rand.Next(0, 100);
                root.AddNode(x);
                expected.Add(x);
            }
            root.TraverseInorder();
            expected.Sort();

            Assert.AreEqual(expected, root.TreeListing);
        }
Exemplo n.º 10
0
        public void InorderTraversal_SetsTreelisting()
        {
            BinaryNode<int> root = new BinaryNode<int>(4);
            BinaryNode<int> node1 = new BinaryNode<int>(1);
            BinaryNode<int> node2 = new BinaryNode<int>(2);
            BinaryNode<int> node3 = new BinaryNode<int>(3);
            BinaryNode<int> node5 = new BinaryNode<int>(5);
            BinaryNode<int> node6 = new BinaryNode<int>(6);
            BinaryNode<int> node7 = new BinaryNode<int>(7);
            BinaryNode<int> node8 = new BinaryNode<int>(8);
            root.LeftChild = node2;
            root.RightChild = node5;
            node2.LeftChild = node1;
            node2.RightChild = node3;
            node5.RightChild = node7;
            node7.LeftChild = node6;
            node7.RightChild = node8;

            root.TraverseInorder();
            List<int> expected = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };

            Assert.AreEqual(expected, root.TreeListing);
        }
Exemplo n.º 11
0
        public void InorderTraversal_PrintsList()
        {
            BinaryNode<int> root = new BinaryNode<int>(4);
            BinaryNode<int> node1 = new BinaryNode<int>(1);
            BinaryNode<int> node2 = new BinaryNode<int>(2);
            BinaryNode<int> node3 = new BinaryNode<int>(3);
            BinaryNode<int> node5 = new BinaryNode<int>(5);
            BinaryNode<int> node6 = new BinaryNode<int>(6);
            BinaryNode<int> node7 = new BinaryNode<int>(7);
            BinaryNode<int> node8 = new BinaryNode<int>(8);
            root.LeftChild = node2;
            root.RightChild = node5;
            node2.LeftChild = node1;
            node2.RightChild = node3;
            node5.RightChild = node7;
            node7.LeftChild = node6;
            node7.RightChild = node8;

            root.TraverseInorderRecursively();
            List<int> expected = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
            List<int> dummy = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };

            Assert.AreEqual(expected, dummy);
        }
 public void SetRight(BinaryNode <T> right)
 {
     _right = right;
 }
 public BinaryNode(T item)
 {
     _item  = item;
     _left  = null;
     _right = null;
 }
 public BinaryOrNode(BinaryNode parent, BinaryNode left, BinaryNode right)
     : base(parent, left, right)
 {
 }
Exemplo n.º 15
0
        private IQueryNode CreateNode(Expression path, JProperty property)
        {
            if (property.Name[0] == '$' && property.Name != "$size")
            {
                // Special functions.
                if (property.Name == "$or")
                {
                    var array = (JArray)property.Value;
                    return(new OrNode(array.Values <JObject>().Select(o => Parse(path, o))));
                }

                if (property.Name == "$nor")
                {
                    var array = (JArray)property.Value;
                    return(new NorNode(array.Values <JObject>().Select(o => Parse(path, o))));
                }

                if (property.Name == "$not")
                {
                    return(new NotNode(Parse(path, (JObject)property.Value)));
                }

                if (property.Name == "$in")
                {
                    var array = (JArray)property.Value;

                    return(new InNode(path, array));
                }

                if (property.Name == "$elemMatch")
                {
                    var parser = new QueryParser(GetEnumerableType(path), _typeDescriptorFactory);

                    var parsedElement = parser.GetType()
                                        .GetMethod("ParseWhere")
                                        .Invoke(parser, new object[] { property.Value }) as Expression;

                    return(new ElementMatchNode(path, parsedElement));
                }

                if (property.Name == "$nin")
                {
                    var array = (JArray)property.Value;

                    return(new NotNode(new InNode(path, array)));
                }

                if (BinaryNode.Arguments.ContainsKey(property.Name))
                {
                    return(new BinaryNode(path, property));
                }

                throw new NotSupportedException(string.Format("{0} Does not support parsing element type {1}", GetType(),
                                                              property.Name));
            }

            Expression left = property.Name == "$size"
                ? SizeNode.GetExpression(_argument, path)
                : _typeDescriptorFactory.Create(path.Type).GetStateProperty(property.Name).CreateGetExpression(path);

            if (property.HasValues && property.Value is JObject)
            {
                // Composite object
                IEnumerable <IQueryNode> innerNodes = property.Values <JObject>().Select(o => Parse(left, o));
                if (left.Type.IsClass)
                {
                    // Check nullability.
                    var extraNode = new BinaryNode(left, new JProperty("$ne", null));
                    innerNodes = new[] { extraNode }.Concat(innerNodes);
                }
                return(new AndNode(innerNodes));
            }

            return(new EqualQueryNode(left, ((JValue)property.Value).Value));
        }
Exemplo n.º 16
0
        private ExpressionNode ParseBrackets()
        {
            var ret = ParseAtom();

            while (Accept(TokenType.LBRACK, TokenType.PERIOD, TokenType.LPAREN))
            {
                var zero   = new IntNode(Position(), 0);
                var length = new BinaryNode(Position(), BinaryOP.SUB, new UnaryNode(Position(), UnaryOP.LENGTH, ret), new IntNode(Position(), 1));

                var pos = Position();

                if (Accept(TokenType.LBRACK))
                {
                    Next();

                    if (Accept(TokenType.COLON))
                    {
                        Next();

                        if (Accept(TokenType.RBRACK))
                        {
                            Next();
                            ret = new SliceNode(pos, ret, zero, length);
                        }
                        else
                        {
                            var end = ParseExpression();

                            Expect(TokenType.RBRACK);
                            Next();

                            ret = new SliceNode(pos, ret, zero, end);
                        }
                    }
                    else
                    {
                        var start = ParseExpression();

                        if (Accept(TokenType.COLON))
                        {
                            Next();

                            if (Accept(TokenType.RBRACK))
                            {
                                Next();
                                ret = new SliceNode(pos, ret, start, length);
                            }
                            else
                            {
                                var end = ParseExpression();

                                Expect(TokenType.RBRACK);
                                Next();

                                ret = new SliceNode(pos, ret, start, end);
                            }
                        }
                        else
                        {
                            Expect(TokenType.RBRACK);
                            Next();

                            ret = new IndexNode(pos, ret, start);
                        }
                    }
                }
                else if (Accept(TokenType.PERIOD))
                {
                    Next();
                    ret = new IndexNode(Position(-1), ret, new StringNode(Position(), ParseIdent().Value));
                }
                else if (Accept(TokenType.LPAREN))
                {
                    Next();

                    var call = new CallNode(pos, ret);

                    while (More() && !Accept(TokenType.RPAREN))
                    {
                        call.Arguments.Add(ParseExpression());

                        if (Accept(TokenType.COMMA))
                        {
                            ExpectNot(TokenType.RPAREN);
                            Next();
                        }
                        else
                        {
                            Expect(TokenType.RPAREN);
                        }
                    }

                    Expect(TokenType.RPAREN);
                    Next();

                    ret = call;
                }
                else
                {
                    Unexpected();
                }
            }

            return(ret);
        }
Exemplo n.º 17
0
        public void VisitBinary(BinaryNode node)
        {
            UpdateLine(node);
            if (node.OP == BinaryOP.AND)
            {
                node.Left.Accept(this);
                var f = asm.NewLabel();
                asm.Not();
                asm.Branch(f);
                node.Right.Accept(this);
                asm.Not();
                asm.Branch(f);
                asm.PushTrue();
                var end = asm.NewLabel();
                asm.Jump(end);
                asm.MarkLabel(f);
                asm.PushFalse();
                asm.MarkLabel(end);
            }
            else if (node.OP == BinaryOP.OR)
            {
                node.Left.Accept(this);
                var t = asm.NewLabel();
                asm.Branch(t);
                node.Right.Accept(this);
                asm.Branch(t);
                asm.PushFalse();
                var end = asm.NewLabel();
                asm.Jump(end);
                asm.MarkLabel(t);
                asm.PushTrue();
                asm.MarkLabel(end);
            }
            else
            {
                node.Left.Accept(this);
                node.Right.Accept(this);

                switch (node.OP)
                {
                case BinaryOP.ADD:
                    asm.Add();
                    break;

                case BinaryOP.SUB:
                    asm.Sub();
                    break;

                case BinaryOP.MUL:
                    asm.Mul();
                    break;

                case BinaryOP.DIV:
                    asm.Div();
                    break;

                case BinaryOP.POW:
                    asm.Pow();
                    break;

                case BinaryOP.MOD:
                    asm.Mod();
                    break;

                case BinaryOP.LSH:
                    asm.Lsh();
                    break;

                case BinaryOP.RSH:
                    asm.Rsh();
                    break;

                case BinaryOP.BIT_NOT:
                    asm.BitNot();
                    break;

                case BinaryOP.BIT_AND:
                    asm.BitAnd();
                    break;

                case BinaryOP.BIT_OR:
                    asm.BitOr();
                    break;

                case BinaryOP.BIT_XOR:
                    asm.BitXor();
                    break;

                case BinaryOP.CONCAT:
                    asm.Concat();
                    break;

                case BinaryOP.EQ:
                    asm.Eq();
                    break;

                case BinaryOP.NE:
                    asm.Ne();
                    break;

                case BinaryOP.DEEP_EQ:
                    asm.DeepEq();
                    break;

                case BinaryOP.DEEP_NE:
                    asm.DeepNe();
                    break;

                case BinaryOP.LT:
                    asm.Lt();
                    break;

                case BinaryOP.GT:
                    asm.Gt();
                    break;

                case BinaryOP.LTE:
                    asm.Lte();
                    break;

                case BinaryOP.GTE:
                    asm.Gte();
                    break;

                default:
                    throw new Exception(node.OP.ToString());
                }
            }
        }
Exemplo n.º 18
0
 //assume distinct values
 public int largestBSTSize(BinaryNode root)
 {
     return(largestBST(root).sizeAny);
 }
Exemplo n.º 19
0
        //----------------------------------------------------------------------
        // Interface methods that have to be implemented for exam
        //----------------------------------------------------------------------

        public void Insert(T x)
        {
            BinaryNode <T> node = Insert(this.root, x);

            this.root = node;
        }
        public static int GetHeight(BinaryNode <T> root)
        {
            var height = new Height();

            return(GetBinaryTreeDiameter(root, height));
        }
Exemplo n.º 21
0
 public static BinaryNode CreateBinaryNode(int topCustomerID, int customerID, int parentID, int placement, int level, int indentedSort)
 {
     BinaryNode binaryNode = new BinaryNode();
     binaryNode.TopCustomerID = topCustomerID;
     binaryNode.CustomerID = customerID;
     binaryNode.ParentID = parentID;
     binaryNode.Placement = placement;
     binaryNode.Level = level;
     binaryNode.IndentedSort = indentedSort;
     return binaryNode;
 }
Exemplo n.º 22
0
 public void AddToBinaryTree(BinaryNode binaryNode)
 {
     base.AddObject("BinaryTree", binaryNode);
 }
 public BinaryOrNode(BinaryNode left, BinaryNode right)
     : base(left, right)
 {
 }
 public virtual void VisitBinaryNode(BinaryNode binop)
 {
 }
Exemplo n.º 25
0
 /// <summary>
 ///     Determine if contains keyword and if it's possible to convert non-keyword types to keyword type
 ///     ie. monday = 4 or month in (may,...,december)
 /// </summary>
 /// <param name="node">Node do check.</param>
 /// <returns>true if can be generalized, else false.</returns>
 private static bool CanBeGeneralized(BinaryNode node) => CanBeGeneralized(node.Left, node.Right);
Exemplo n.º 26
0
 public void BuildJoin(BinaryNode node)
 {
     BuildJoin((dynamic)node.Left, (dynamic)node.Right, node.Operator);
 }
Exemplo n.º 27
0
    public StateType adjustAgentStateTypeForBinaryNode(BinaryNode node, int playerNumber)
    {
        StateType nodeStateType = (StateType)node.getBinary();

        if (playerNumber == 1)
        {
            if (node.hasFlag(StateType.ST_Agent1))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent1);
                nodeStateType = nodeStateType | StateType.ST_Agent;
            }

            if (node.hasSomeFlag(StateType.ST_Agent2 | StateType.ST_Agent3 | StateType.ST_Agent4))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent2);
                nodeStateType = nodeStateType & (~StateType.ST_Agent3);
                nodeStateType = nodeStateType & (~StateType.ST_Agent4);
                nodeStateType = nodeStateType | StateType.ST_EnemyAgent;
            }
        }
        else if (playerNumber == 2)
        {
            if (node.hasFlag(StateType.ST_Agent2))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent2);
                nodeStateType = nodeStateType | StateType.ST_Agent;
            }

            if (node.hasSomeFlag(StateType.ST_Agent1 | StateType.ST_Agent3 | StateType.ST_Agent4))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent1);
                nodeStateType = nodeStateType & (~StateType.ST_Agent3);
                nodeStateType = nodeStateType & (~StateType.ST_Agent4);
                nodeStateType = nodeStateType | StateType.ST_EnemyAgent;
            }
        }
        else if (playerNumber == 3)
        {
            if (node.hasFlag(StateType.ST_Agent3))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent3);
                nodeStateType = nodeStateType | StateType.ST_Agent;
            }

            if (node.hasSomeFlag(StateType.ST_Agent1 | StateType.ST_Agent2 | StateType.ST_Agent4))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent1);
                nodeStateType = nodeStateType & (~StateType.ST_Agent2);
                nodeStateType = nodeStateType & (~StateType.ST_Agent4);
                nodeStateType = nodeStateType | StateType.ST_EnemyAgent;
            }
        }
        else if (playerNumber == 4)
        {
            if (node.hasFlag(StateType.ST_Agent4))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent4);
                nodeStateType = nodeStateType | StateType.ST_Agent;
            }

            if (node.hasSomeFlag(StateType.ST_Agent1 | StateType.ST_Agent2 | StateType.ST_Agent3))
            {
                nodeStateType = nodeStateType & (~StateType.ST_Agent1);
                nodeStateType = nodeStateType & (~StateType.ST_Agent2);
                nodeStateType = nodeStateType & (~StateType.ST_Agent3);
                nodeStateType = nodeStateType | StateType.ST_EnemyAgent;
            }
        }

        return(nodeStateType);
    }
Exemplo n.º 28
0
 private string InOrder(BinaryNode <T> node)
 {
     return((node.left != null ? InOrder(node.left) + " " : "") + node.data + (node.right != null ? " " + InOrder(node.right) : ""));
 }
 public virtual void VisitBinaryNode(BinaryNode binop)
 {
     binop.Left.Visit(this);
     binop.Right.Visit(this);
 }
Exemplo n.º 30
0
 private static bool IsTripletPresentWithZeroSum(BinaryNode node)
 {
     return(false);
 }
Exemplo n.º 31
0
 internal BinaryEnumerator(BinarySearchTree <T> tree)
 {
     _tree        = tree;
     _currentNode = null;
     _leftNode    = _rightNode = _tree._root;
 }
Exemplo n.º 32
0
    private Info largestBST(BinaryNode root)
    {
        Info info = new Info {
            sizeRooted = 0, sizeAny = 0, isBST = false
        };

        if (root == null)
        {
            return(info);
        }


        if (root.left == null && root.right == null)
        {
            info.isBST      = true;
            info.sizeRooted = 1;
            info.sizeAny    = 1;

            info.minIfBst = root.value;
            info.maxIfBst = root.value;
            return(info);
        }

        Info leftSide = largestBST(root.left), rightSide = largestBST(root.right);

        if (root.left != null && root.right == null)
        {
            if (leftSide.isBST && leftSide.maxIfBst < root.value)
            {
                info.isBST      = true;
                info.sizeRooted = 1 + leftSide.sizeRooted;
                info.sizeAny    = 1 + leftSide.sizeAny;
                info.minIfBst   = Math.Min(leftSide.minIfBst, root.value);
                info.maxIfBst   = Math.Max(leftSide.maxIfBst, root.value);
            }
            else
            {
                info.sizeAny = leftSide.sizeAny;
            }
        }
        else if (root.left == null && root.right != null)
        {
            if (rightSide.isBST && rightSide.minIfBst > root.value)
            {
                info.isBST      = true;
                info.sizeRooted = 1 + rightSide.sizeRooted;
                info.sizeAny    = 1 + rightSide.sizeAny;
                info.minIfBst   = Math.Min(rightSide.minIfBst, root.value);
                info.maxIfBst   = Math.Max(rightSide.maxIfBst, root.value);
            }
            else
            {
                info.sizeAny = rightSide.sizeAny;
            }
        }
        else
        {
            if (leftSide.isBST && rightSide.isBST && leftSide.maxIfBst < root.value && rightSide.minIfBst > root.value)
            {
                info.isBST      = true;
                info.sizeRooted = 1 + leftSide.sizeRooted + rightSide.sizeRooted;
                info.sizeAny    = 1 + leftSide.sizeAny + rightSide.sizeAny;
                info.minIfBst   = Math.Min(leftSide.minIfBst, root.value);
                info.minIfBst   = Math.Min(rightSide.minIfBst, info.minIfBst);
                info.maxIfBst   = Math.Max(leftSide.maxIfBst, root.value);
                info.maxIfBst   = Math.Max(rightSide.maxIfBst, info.maxIfBst);
            }
            else
            {
                info.sizeAny = Math.Max(rightSide.sizeAny, leftSide.sizeAny);
            }
        }

        return(info);
    }
Exemplo n.º 33
0
 /// <summary>
 /// Устанавливает перечислитель в его начальное положение, т. е. перед первым элементом односвязного списка.
 /// </summary>
 public void Reset()
 {
     _currentNode = null;
     _leftNode    = _rightNode = _tree._root;
 }
Exemplo n.º 34
0
    public static void Print(this BinaryNode root, int topMargin = 2, int leftMargin = 2)
    {
        if (root == null)
        {
            return;
        }
        int rootTop = Console.CursorTop + topMargin;
        var last    = new List <NodeInfo>();
        var next    = root;

        for (int level = 0; next != null; level++)
        {
            var item = new NodeInfo {
                Node = next, Text = next.Item.ToString(" 0 ")
            };
            if (level < last.Count)
            {
                item.StartPos = last[level].EndPos + 1;
                last[level]   = item;
            }
            else
            {
                item.StartPos = leftMargin;
                last.Add(item);
            }
            if (level > 0)
            {
                item.Parent = last[level - 1];
                if (next == item.Parent.Node.Left)
                {
                    item.Parent.Left = item;
                    item.EndPos      = Math.Max(item.EndPos, item.Parent.StartPos);
                }
                else
                {
                    item.Parent.Right = item;
                    item.StartPos     = Math.Max(item.StartPos, item.Parent.EndPos);
                }
            }
            next = next.Left ?? next.Right;
            for (; next == null; item = item.Parent)
            {
                Print(item, rootTop + 2 * level);
                if (--level < 0)
                {
                    break;
                }
                if (item == item.Parent.Left)
                {
                    item.Parent.StartPos = item.EndPos;
                    next = item.Parent.Node.Right;
                }
                else
                {
                    if (item.Parent.Left == null)
                    {
                        item.Parent.EndPos = item.StartPos;
                    }
                    else
                    {
                        item.Parent.StartPos += (item.StartPos - item.Parent.EndPos) / 2;
                    }
                }
            }
        }
        Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1);
    }
Exemplo n.º 35
0
 /// <summary>
 /// Освобождает все ресурсы, занятые модулем <see cref="BinaryEnumerator"/>.
 /// </summary>
 public void Dispose()
 {
     _tree        = null;
     _currentNode = _leftNode = _rightNode = null;
 }
Exemplo n.º 36
0
        private ExpressionNode ParseInterpolatedString()
        {
            Expect(TokenType.INTERPOLATED_STRING);
            var pos = Position();
            var str = Current().Text;

            Next();

            var parts = new List <ExpressionNode>();

            bool inExpr = false;
            int  level  = 0;
            var  start  = 0;

            int i = 0;

            char peek() => str[i];
            string current() => str.Substring(start, i - start - 1);

            bool accept(char c)
            {
                if (peek() == c)
                {
                    i++;
                    return(true);
                }
                return(false);
            }

            void addString()
            {
                var cur = current();

                parts.Add(new StringNode(new SourcePosition(pos.Line, pos.Column + i - cur.Length + 1), cur));
            }

            void addExpression()
            {
                var cur    = current();
                var lexer  = new Lexer.Lexer(cur, new SourcePosition(pos.Line - 1, 0 /* @TODO wrong column number */));
                var parser = new Parser("<interpolated string expression>", lexer.Tokenize());

                parts.Add(parser.ParseExpression());
            }

            while (i < str.Length)
            {
                if (inExpr)
                {
                    if (accept('{'))
                    {
                        level++;
                    }
                    else if (accept('}'))
                    {
                        level--;
                    }

                    if (level == 0)
                    {
                        addExpression();
                        inExpr = false;
                        start  = i;
                    }
                    else
                    {
                        i++;
                    }
                }
                else
                {
                    if (accept('{'))
                    {
                        addString();
                        inExpr = true;
                        level  = 1;
                        start  = i;
                    }
                    else
                    {
                        i++;
                    }
                }
            }

            if (inExpr)
            {
                throw new ParseException("String interpolation expression not ended");
            }
            if (start != i)
            {
                i++;
                addString();
            }

            if (parts.Count == 1)
            {
                return(parts[0]);
            }
            else
            {
                var ret = new BinaryNode(pos /* @TODO: wrong column number */, BinaryOP.CONCAT, parts[0], parts[1]);

                for (var j = 2; j < parts.Count; j++)
                {
                    ret = new BinaryNode(pos /* @TODO: wrong column number */, BinaryOP.CONCAT, ret, parts[j]);
                }

                return(ret);
            }
        }
Exemplo n.º 37
0
 public void RemoveNode(PathNode pathNode)
 {
     if (root.pathNode == pathNode)
     {
         // It's the root
         //debugCodePath += "RR" + root + "; ";
         BinaryNode prevRoot = root;
         if (root.left == null && root.right == null)
         {
             // Both are null
             root = null;
             // Tree is dead
         }
         else
         {
             // Atleast one has something
             if (root.left == null && root.right != null)
             {
                 // Has right but no left
                 root = root.right;
             }
             else
             {
                 if (root.right == null && root.left != null)
                 {
                     // Has left but no right
                     root = root.left;
                 }
                 else
                 {
                     // Has both right and left
                     if (root.left.right == null)
                     {
                         // Root left has no right
                         root.left.right = root.right;
                         root            = root.left;
                     }
                     else
                     {
                         // Root left has a right
                         BinaryNode leafRight = getLeafRight(root.left);
                         root = leafRight.right;
                         if (leafRight.right.left != null)
                         {
                             // This leaf has a left
                             leafRight.right = leafRight.right.left;
                         }
                         leafRight.right = null;
                         root.left       = leafRight;
                         root.right      = prevRoot.right;
                     }
                 }
             }
         }
     }
     else
     {
         int pathFvalue = pathNode.fValue;
         removeNode(root, pathNode, pathFvalue);
     }
     totalNodes--;
 }
Exemplo n.º 38
0
 private void removeNode(BinaryNode node, PathNode pathNode, int pathFvalue)
 {
     if (pathFvalue <= node.pathNode.fValue)
     {
         // Check left
         // Is it this left?
         if (node.left != null)
         {
             if (node.left.pathNode == pathNode)
             {
                 // It's this left one!
                 BinaryNode del = node.left;
                 //debugCodePath += "RNL" + del + "; ";
                 if (del.left == null && del.right == null)
                 {
                     // Both are null
                     node.left = null;
                 }
                 else
                 {
                     // Atleast one has something
                     if (del.left == null && del.right != null)
                     {
                         // Has right but no left
                         node.left = del.right;
                     }
                     else
                     {
                         if (del.right == null && del.left != null)
                         {
                             // Has left but no right
                             node.left = del.left;
                         }
                         else
                         {
                             // Has both right and left
                             if (del.left.right == null)
                             {
                                 // Root left has no right
                                 del.left.right = del.right;
                                 node.left      = del.left;
                             }
                             else
                             {
                                 // Root left has a right
                                 BinaryNode leafRight = getLeafRight(del.left);
                                 node.left = leafRight.right;
                                 if (leafRight.right.left != null)
                                 {
                                     // This leaf has a left
                                     leafRight.right = leafRight.right.left;
                                 }
                                 leafRight.right = null;
                                 node.left.left  = leafRight;
                                 node.left.right = del.right;
                             }
                         }
                     }
                 }
             }
             else
             {
                 // Not this left
                 // Check next one
                 removeNode(node.left, pathNode, pathFvalue);
             }
         }
     }
     else
     {
         // Check right
         // Is it this right?
         if (node.right != null)
         {
             if (node.right.pathNode == pathNode)
             {
                 // It's this right one!
                 BinaryNode del = node.right;
                 //debugCodePath += "RNR" + del + "; ";
                 if (del.left == null && del.right == null)
                 {
                     // Both are null
                     node.right = null;
                 }
                 else
                 {
                     // Atleast one has something
                     if (del.left == null && del.right != null)
                     {
                         // Has right but no left
                         node.right = del.right;
                     }
                     else
                     {
                         if (del.right == null && del.left != null)
                         {
                             // Has left but no right
                             node.right = del.left;
                         }
                         else
                         {
                             // Has both right and left
                             if (del.left.right == null)
                             {
                                 // Root left has no right
                                 del.left.right = del.right;
                                 node.right     = del.left;
                             }
                             else
                             {
                                 // Root left has a right
                                 BinaryNode leafRight = getLeafRight(del.left);
                                 node.right = leafRight.right;
                                 if (leafRight.right.left != null)
                                 {
                                     // This leaf has a left
                                     leafRight.right = leafRight.right.left;
                                 }
                                 leafRight.right  = null;
                                 node.right.left  = leafRight;
                                 node.right.right = del.right;
                             }
                         }
                     }
                 }
             }
             else
             {
                 // Not this right
                 // Check next one
                 removeNode(node.right, pathNode, pathFvalue);
             }
         }
     }
 }
Exemplo n.º 39
0
        //private string debugString;
        //private string debugCodePath;

        public BinaryTree()
        {
            //BinaryNode.nextId = 0;
            root = null;
            //debugCodePath = "NEW: ";
        }
Exemplo n.º 40
0
 private bool _conditionEndPointRightBranchChild(BinaryNode node)
 {
     return node.LeftChild != null
            && node.LeftChild.Type == NodeType.ConditionEndPoint
            && node.LeftChild.RightAncestor == node;
 }
    private static GameObject LoadRecursionOnce(GameObject parentGo, BinaryNode domNode)
    {
        GameObject gameObject = null;
        string     nodeAttr   = GameSerializer.GetNodeAttr(domNode, "ON");

        if (parentGo != null)
        {
            for (int i = 0; i < parentGo.transform.childCount; i++)
            {
                if (parentGo.transform.GetChild(i).name.Equals(nodeAttr))
                {
                    gameObject = parentGo.transform.GetChild(i).gameObject;
                    break;
                }
            }
        }
        if (gameObject == null)
        {
            string nodeAttr2 = GameSerializer.GetNodeAttr(domNode, "PFB");
            if (nodeAttr2 != null && nodeAttr2.get_Length() != 0)
            {
                object resource = GameSerializer.GetResource(nodeAttr2, typeof(GameObject));
                if (resource == null || !(resource is GameObject))
                {
                    Debug.LogError(nodeAttr2 + " 不存在或者类型错误,请重新导出该场景");
                    gameObject = new GameObject();
                }
                else
                {
                    GameObject gameObject2 = resource as GameObject;
                    bool       activeSelf  = gameObject2.activeSelf;
                    gameObject2.SetActive(false);
                    gameObject = (GameObject)Object.Instantiate(gameObject2);
                    gameObject2.SetActive(activeSelf);
                }
            }
            else
            {
                gameObject = new GameObject();
            }
        }
        Vector3 localScale = gameObject.transform.localScale;

        gameObject.name = GameSerializer.GetNodeAttr(domNode, "ON");
        if (parentGo != null)
        {
            gameObject.transform.parent = parentGo.transform;
        }
        gameObject.transform.localScale = localScale;
        GameSerializer.DeserializeObject(domNode, gameObject);
        gameObject.SetActive(false);
        GameSerializer.InitComponets(domNode, gameObject);
        for (int j = 0; j < domNode.GetChildNum(); j++)
        {
            BinaryNode child = domNode.GetChild(j);
            if (child.GetName() == "CHD")
            {
                GameSerializer.LoadRecursionOnce(gameObject, child);
            }
        }
        return(gameObject);
    }
Exemplo n.º 42
0
        public List <BinaryNode> Find(BinaryNode root1, BinaryNode root2)
        {
            if (root1 == null || root2 == null)
            {
                return(new List <BinaryNode>());
            }

            // Create two stacks for preorder traversals - we push nodes onto the stacks
            // until we find leaves, then we compare
            var s1 = new Stack <BinaryNode>();

            s1.Push(root1);
            var s2 = new Stack <BinaryNode>();

            s2.Push(root2);

            while (s1.Count > 0 && s2.Count > 0)
            {
                // not sure I understand this criteria given above while condition
                if (s1.Count == 0 || s2.Count == 0)
                {
                    return(new List <BinaryNode>());
                }

                // Do iterative traversal of first tree
                var temp1 = s1.Pop();
                while (temp1 != null && temp1.IsLeaf() == false)
                {
                    s1.Push(temp1.Right);
                    s1.Push(temp1.Left);

                    temp1 = s1.Pop();
                }

                // Do iterative traversal of the second tree
                var temp2 = s2.Pop();
                while (temp2 != null && temp2.IsLeaf() == false)
                {
                    s2.Push(temp2.Right);
                    s2.Push(temp2.Left);

                    temp2 = s2.Pop();
                }

                // if we found leaves in both trees
                if (temp1 != null && temp2 != null)
                {
                    if (temp1.Value != temp2.Value)
                    {
                        return new List <BinaryNode>()
                               {
                                   temp1, temp2
                               }
                    }
                    ;
                }
            }

            return(new List <BinaryNode>());
        }
    }
    public static object GetObject(BinaryNode currNode)
    {
        string nodeAttr = GameSerializer.GetNodeAttr(currNode, "NULL");
        object obj      = null;

        if (nodeAttr != null)
        {
            return(obj);
        }
        string nodeAttr2 = GameSerializer.GetNodeAttr(currNode, "Type");
        string nodeAttr3 = GameSerializer.GetNodeAttr(currNode, "V");
        string nodeAttr4 = GameSerializer.GetNodeAttr(currNode, "JT");

        if ("Arr".Equals(nodeAttr4))
        {
            if (nodeAttr2 != null)
            {
                string typeStr = nodeAttr2.Replace("[]", string.Empty);
                Type   type    = GameSerializer.GetType(typeStr);
                if (type == null)
                {
                    Debug.LogError("Array type " + nodeAttr2 + " create failed!");
                    return(null);
                }
                Array array = Array.CreateInstance(type, currNode.GetChildNum());
                for (int i = 0; i < array.get_Length(); i++)
                {
                    array.SetValue(GameSerializer.GetObject(currNode.GetChild(i)), i);
                }
                obj = array;
            }
        }
        else if ("Cus".Equals(nodeAttr4))
        {
            if (nodeAttr2 != null)
            {
                Type type2 = GameSerializer.GetType(nodeAttr2);
                ICustomizedObjectSerializer objectSerlizer = GameSerializer.GetObjectSerlizer(type2);
                if (objectSerlizer != null && objectSerlizer is ICustomInstantiate)
                {
                    obj = ((ICustomInstantiate)objectSerlizer).Instantiate(currNode);
                }
                else
                {
                    obj = GameSerializer.CreateInstance(type2);
                }
                if (obj == null)
                {
                    return(null);
                }
                if (objectSerlizer != null)
                {
                    objectSerlizer.ObjectDeserialize(ref obj, currNode);
                }
            }
        }
        else if ("Enum".Equals(nodeAttr4))
        {
            if (nodeAttr2 != null)
            {
                Type type3 = GameSerializer.GetType(nodeAttr2);
                obj = Enum.ToObject(type3, int.Parse(nodeAttr3));
            }
        }
        else if ("Pri".Equals(nodeAttr4))
        {
            if (nodeAttr2 != null)
            {
                obj = Convert.ChangeType(nodeAttr3, GameSerializer.GetType(nodeAttr2));
            }
        }
        else if ("Ref".Equals(nodeAttr4))
        {
            Object gameObjectFromPath = GameSerializer.GetGameObjectFromPath(nodeAttr3, nodeAttr2);
            if (gameObjectFromPath != null)
            {
                if (gameObjectFromPath is GameObject)
                {
                    if (nodeAttr2 != null)
                    {
                        string pureType = GameSerializer.GetPureType(nodeAttr2);
                        if (!"GameObject".Equals(pureType))
                        {
                            obj = (gameObjectFromPath as GameObject).GetComponent(pureType);
                            if (obj == null)
                            {
                                Debug.LogError("No " + pureType + " component found in " + nodeAttr3);
                            }
                        }
                        else
                        {
                            obj = gameObjectFromPath;
                        }
                    }
                }
                else
                {
                    obj = gameObjectFromPath;
                }
            }
            else
            {
                obj = null;
                Debug.LogError("Load gameobject " + nodeAttr3 + " failed!");
            }
        }
        else if ("Com".Equals(nodeAttr4))
        {
            obj = GameSerializer.CreateInstance(nodeAttr2);
            if (obj == null)
            {
                return(null);
            }
            MemberInfo[] members = obj.GetType().GetMembers();
            for (int j = 0; j < members.Length; j++)
            {
                if (GameSerializer.IsMINeedExport(members[j]))
                {
                    BinaryNode binaryNode = currNode.SelectSingleNode(members[j].get_Name());
                    if (binaryNode != null)
                    {
                        try
                        {
                            object @object = GameSerializer.GetObject(binaryNode);
                            if (binaryNode != null && @object != null)
                            {
                                GameSerializer.SetMIValue(members[j], obj, @object);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError(string.Concat(new object[]
                            {
                                "Set field value failed! Field ",
                                members[j].get_Name(),
                                " in ",
                                obj.GetType(),
                                "e:",
                                ex
                            }));
                        }
                    }
                }
            }
        }
        return(obj);
    }
 public void SetLeft(BinaryNode <T> left)
 {
     _left = left;
 }
 public static IEnumerator GetObjectAsync(BinaryNode currNode, ObjectHolder holder)
 {
     GameSerializer.< GetObjectAsync > c__Iterator38 <GetObjectAsync> c__Iterator = new GameSerializer.< GetObjectAsync > c__Iterator38();
 public Excercise2()
 {
     Root = null;
 }
Exemplo n.º 47
0
 public void SetRoot(BinaryNode node)
 {
     _root = node;
 }