public void init(LeafNode myNode){ if (linkToParent != null) { GameObject.Destroy(linkToParent.gameObject); linkToParent = null; } foreach(NodeVis nVis in childs){ GameObject.Destroy(nVis.gameObject); } childs.Clear (); node = myNode; if (parent != null) { GameObject link = (GameObject)GameObject.Instantiate(treeVis.linkPrefab.gameObject); link.transform.parent = this.transform; link.transform.localScale = Vector3.one; link.transform.localPosition = Vector3.zero; linkToParent = link.GetComponent<LinkVis>(); linkToParent.setUpLine(Vector3.zero,parent.transform.position-transform.position); } if (myNode is ParentNode && ((ParentNode)myNode).childNodes != null) { foreach(LeafNode LNode in ((ParentNode)myNode).childNodes){ AddChild (LNode); } } }
public void Test_InnerNode_Merge_Test() { var leftInnerNode = new InnerNode<int, int>(3); var leaf = new LeafNode<int, int>(3); leaf.Keys.Add(1); leaf.Values.Add(new List<int>()); leaf.Values[0].Add(1); leftInnerNode.Children.Add(leaf); leaf = new LeafNode<int, int>(3); leaf.Keys.Add(2); leaf.Values.Add(new List<int>()); leaf.Values[0].Add(2); leftInnerNode.Children.Add(leaf); leftInnerNode.Keys.Add(1); var rightInnerNode = new InnerNode<int, int>(3); leaf = new LeafNode<int, int>(3); leaf.Keys.Add(3); leaf.Values.Add(new List<int>()); leaf.Values[0].Add(3); rightInnerNode.Children.Add(leaf); rightInnerNode.Keys.Add(4); leftInnerNode.Merge(rightInnerNode); Assert.AreEqual(0, rightInnerNode.Keys.Count); Assert.AreEqual(0, rightInnerNode.Children.Count); Assert.AreEqual(2, leftInnerNode.Keys.Count); Assert.AreEqual(3, leftInnerNode.Children.Count); }
public Snzi () { nodes = new ISnziNode[count]; root = new RootNode (); for (int i = 0; i < count; i++) nodes[i] = new LeafNode (root); }
public TextureData(LeafNode node, string texname, bool isTgaMips) { this.type = node.Name; this.texname = texname; this.data = node.ByteArrayData; if (isTgaMips) { levels = new Dictionary <int, byte[]>(); } }
public override void Clear() { count = 0; version = 0; leafList = null; for (int i = 0; i < width; i++) { table[i] = new HashTable <XFastNode>(); } }
public void AddOnLeafShouldCreateAnotherLeafIfKeysAreEqual() { var leaf = new LeafNode <string> (1, "hello"); var result = (LeafNode <string>)leaf.Add(1, "there"); Assert.That(result.Key, Is.EqualTo(1)); Assert.That(result.Value, Is.EqualTo("there")); Assert.That(result.Count, Is.EqualTo(1)); }
public void Test_LeafNode_Insert() { var node = new LeafNode<int, int>(3); for (int i = 1; i <= 3; i++) node.Insert(i, i); Assert.IsTrue(node.IsFull()); Assert.AreEqual(1, node.Keys[0]); Assert.AreEqual(2, node.Keys[1]); Assert.AreEqual(3, node.Keys[2]); }
internal override bool TryToInsert(LeafNode node, out Node treeNode) { var newTreeNode = new InternalNode(); BoundingBox.CreateMerged(ref BoundingBox, ref node.BoundingBox, out newTreeNode.BoundingBox); newTreeNode.ChildA = this; newTreeNode.ChildB = node; treeNode = newTreeNode; return(true); }
public void AddOnLeafShouldCreateAnotherLeafIfKeysAreEqual () { var leaf = new LeafNode<string> (1, "hello"); var result = (LeafNode<string>) leaf.Add (1, "there"); Assert.That (result.Key, Is.EqualTo (1)); Assert.That (result.Value, Is.EqualTo ("there")); Assert.That (result.Count, Is.EqualTo (1)); }
/// <summary> /// Splits this node into subnodes by creating a new "left" and /// a new "right" node and adds the (key,value) to the appropriate subnode. /// </summary> private (Node, Node) SplitAndInsert(TKey key, TValue value, ConcurrentBTreeDictionary <TKey, TValue> tree) { var iSplit = (this.count + 1) / 2; var leftCount = iSplit; var rightCount = this.count - iSplit; var lKeys = new TKey[tree.LeafNodeChildren]; var rKeys = new TKey[tree.LeafNodeChildren]; var lValues = new TValue[tree.LeafNodeChildren]; var rValues = new TValue[tree.LeafNodeChildren]; Array.Copy(this.keys, 0, lKeys, 0, leftCount); Array.Copy(this.keys, iSplit, rKeys, 0, rightCount); Array.Copy(this.values, 0, lValues, 0, leftCount); Array.Copy(this.values, iSplit, rValues, 0, rightCount); TKey[] nKeys; TValue[] nValues; int count; if (tree.Comparer.Compare(rKeys[0], key) < 0) { nKeys = rKeys; nValues = rValues; count = rightCount; ++rightCount; } else { nKeys = lKeys; nValues = lValues; count = leftCount; ++leftCount; } // Find the place where the item would be if it had been present. int idx = Array.BinarySearch(nKeys, 0, count, key, tree.Comparer); if (idx >= 0) { throw new ArgumentException("Duplicate key."); } idx = ~idx; if (idx < count) { // Make a 'hole' if the place is not at the end of the items. Array.Copy(nKeys, idx, nKeys, idx + 1, count - idx); Array.Copy(nValues, idx, nValues, idx + 1, count - idx); } nKeys[idx] = key; nValues[idx] = value; var left = new LeafNode(lKeys, lValues, leftCount, leftCount); var right = new LeafNode(rKeys, rValues, rightCount, rightCount); return(left, right); }
/// <summary> /// Display contents of tree by level (breadth first). /// </summary> /// </exclude> public void Dump() { int level = 0; Node first; for (; ;) { TreePath branchPath = new TreePath(this, level); first = branchPath.TopNode; if (first is LeafNode) { break; } InternalNode branch = (InternalNode)first; Console.Write("L{0}: ", level); for (; ;) { branch.Dump(); branch = (InternalNode)branchPath.TraverseRight(); if (branch == null) { break; } Console.Write(" | "); } ++level; Console.WriteLine(); } TreePath leafPath = new TreePath(this, level); Console.Write("L{0}: ", level); for (LeafNode leaf = (LeafNode)first; ;) { leaf.Dump(); leaf = (LeafNode)leafPath.TraverseRight(); if (leaf == null) { break; } if (leafPath.IsFirstChild) { Console.Write(" | "); } else { Console.Write("|"); } } Console.WriteLine(); }
public void setup(string path) { string[] lines = File.ReadAllLines(path); string size = lines[0], depth = lines[1]; Int32.TryParse(size, out this.size); Int32.TryParse(depth, out this.maxDepth); //set up Node pnode; for (int i = 2; i < lines.Length; i++) { pnode = root; //Debug.Log(lines[i]); string[] subs = lines[i].Split(' '); //path in the string that leads to the leaf node string pathStr = subs[0]; int pathNum; //Pass through all nodes, and stop before leaf for (int j = 0; j < pathStr.Length - 1; j++) { Int32.TryParse(pathStr[j].ToString(), out pathNum); //check to see if the node needs its array if (pnode.node == null) { pnode.node = new Node[8]; } //check to see if it has not been created already if (pnode.node[pathNum] == null) { pnode.node[pathNum] = new Node(); //creation } pnode = pnode.node[pathNum]; //transfer } //verify if current nodes has childred alreday if (pnode.node == null) { pnode.node = new Node[8]; } //generate a leafnode Int32.TryParse(pathStr[pathStr.Length - 1].ToString(), out pathNum); pnode.node[pathNum] = new LeafNode(); //add color from file to the leafnode LeafNode tmp = (LeafNode)pnode.node[pathNum]; float.TryParse(subs[1], out tmp.color.r); float.TryParse(subs[2], out tmp.color.g); float.TryParse(subs[3], out tmp.color.b); } }
internal Enumerator(ImmutableTreeList <T> list, TreeSpan span, Builder builder) { _root = list._root; _span = span; _builder = builder; _version = builder?.Version ?? 0; _index = -1; _leafNode = null; _leafIndex = -1; _current = default; }
public LeafNode(TValue data, BlockNode parent, LeafNode prev) { Parent = parent; Data = data; Prev = prev; if (prev != null) { Prev.Next = this; } Next = null; }
public void TestDecode() { var n = new LeafNode { Value = Encoding.ASCII.GetBytes("hello") }; var code = n.Encode(); var m = MPTNode.Decode(code); Assert.IsInstanceOfType(m, n.GetType()); }
unsafe void ReadHeader(LeafNode node) { if (node.DataSegment.Count < 12) throw new Exception("Anm Header malformed"); fixed(byte *bytes = node.DataSegment.Array) { FrameCount = *(int *)(&bytes[node.DataSegment.Offset]); Interval = *(float *)(&bytes[node.DataSegment.Offset + 4]); ChannelType = *(int *)(&bytes[node.DataSegment.Offset + 8]); } }
public void LeafNode_provides_name() { // ARRANGE var node = new LeafNode(name: "name", ServiceProvider()); // ACT var result = node.Name; // ASSERT Assert.Equal("name", result); }
private void CreateBehaviourTree() { _run = new LeafNode(Run); _celebrate = new LeafNode(Celebrate); _pickNearestCover = new LeafNode(PickNearestCover); _alreadyHasCover = new LeafNode(AlreadyHasCover); _takeCover = new LeafNode(TakeCover); _reload = new LeafNode(Reload); _randomlyTryToPickNewCover = new LeafNode(RandomlyTryToPickNewCover); _hasStandingSpot = new LeafNode(HasStandingSpot); _pickStandingSpot = new LeafNode(PickStandingSpot); _aimAndFire = new LeafNode(AimAndFire); //_considerationTaken = new SuceederNode(_randomlyTryToPickNewCover); //_shouldReload = new TestNode(_reload, ShouldReload); _checkCoverPicked = new SelectorNode(new List <Node> { _alreadyHasCover, _pickNearestCover }); _goToNearestCover = new SequenceNode(new List <Node> { _checkCoverPicked, _run }); _isNotInCover = new TestNode(_goToNearestCover, IsNotInCover); _takeCoverAndReload = new SequenceNode(new List <Node> { _takeCover, _reload }); //_isNotFiring1 = new TestNode(_takeCoverReloadAndConsiderFlanking, IsNotFiring); _isMagazineNotEmpty = new TestNode(_aimAndFire, IsMagazineNotEmpty); _isMagazineEmpty = new TestNode(_takeCoverAndReload, () => !IsMagazineNotEmpty()); _isSuppresed = new TestNode(_takeCoverAndReload, () => !IsNotSuppressed()); _isNotSuppresed = new TestNode(_isMagazineNotEmpty, IsNotSuppressed); _checkStandingSpotPicked = new SelectorNode(new List <Node> { _hasStandingSpot, _pickStandingSpot }); _getOutOfCover = new SequenceNode(new List <Node> { _checkStandingSpotPicked, _run }); //_isNotFiring2 = new TestNode(_getOutOfCover, IsNotFiring); _tryToFireAtEnemy = new SequenceNode(new List <Node> { _getOutOfCover, _isNotSuppresed }); _engage = new SelectorNode(new List <Node> { _isNotInCover, _isSuppresed, _isMagazineEmpty, _randomlyTryToPickNewCover, _tryToFireAtEnemy }); _isEnemyPresent = new TestNode(_engage, IsEnemyPresent); _rootNode = new SelectorNode(new List <Node> { _isEnemyPresent, _celebrate }); }
public void RanmeItemProperty_defaults_to_exception() { // ARRANGE var node = new LeafNode("name", ServiceProvider()); // ACT var result = Assert.Throws <PSNotSupportedException>(() => node.RenameItemProperty("propertyName", "newPropertyName")); // ASSERT Assert.Equal($"Node(name='name') doesn't provide an implementation of capability 'IRenameItemProperty'.", result.Message); }
static Node NodeOf(LeafNode node, int offset, int length) { if (length <= BLOCK_SIZE) { return(node.SubNode(offset, offset + length)); } // Splits on a block boundary. int half = ((length + BLOCK_SIZE) >> 1) & BLOCK_MASK; return(new CompositeNode(NodeOf(node, offset, half), NodeOf(node, offset + half, length - half))); }
internal LeafNode GetLastLeaf() { for (Node node = _root; ; node = ((InternalNode)node).LastChild) { LeafNode leaf = node as LeafNode; if (leaf != null) { return(leaf); } } }
private void GenerateRecordSet(RecordSet recordSet) { IDictionaryEnumerator ide = _nodeStore.GetEnumerator(); while (ide.MoveNext()) { if (ide.Value is LeafNode) { LeafNode leaf = (LeafNode)ide.Value; List <string> keys = leaf.Keys; if (_isGrouped) { RecordRow row = recordSet.CreateRow() as RecordRow; if (leaf.AttributeValues != null) { foreach (KeyValuePair <string, object> entry in leaf.AttributeValues.Values) { if (recordSet.Columns[entry.Key].DataType == ColumnDataType.Object) { recordSet.Columns[entry.Key].DataType = RecordSet.ToColumnDataType(entry.Value); } row[entry.Key] = entry.Value; } } row.Tag = keys; recordSet.Rows.Add(row); } else { foreach (string key in keys) { RecordRow row = recordSet.CreateRow() as RecordRow; if (leaf.AttributeValues != null) { foreach (KeyValuePair <string, object> entry in leaf.AttributeValues.Values) { if (recordSet.Columns[entry.Key].DataType == ColumnDataType.Object) { recordSet.Columns[entry.Key].DataType = RecordSet.ToColumnDataType(entry.Value); } row[entry.Key] = entry.Value; } } row[QueryKeyWords.KeyColumn] = key; recordSet.Rows.Add(row); } } } else { (ide.Value as MultiRootTree).GenerateRecordSet(recordSet); } } }
public void CopyItemPropertyParameters_defaults_to_null() { // ARRANGE var destinationNode = new LeafNode("name", ServiceProvider()); // ACT var result = destinationNode.CopyItemPropertyParameters("sourcePath", "sourceProperty", "destinationPath", "destinationProperty"); // ASSERT Assert.Null(result); }
private void GenInterfaceMember(LeafNode node, CodeTypeDeclaration parentInterfaceContainer) { var summary = $"Path: {node.ResourcePath}\nValue:\n{node.Value}"; if (node.FormatStringValue is null) { var member = new CodeMemberProperty { Name = node.MemberName, Type = Statics.String, HasGet = true, HasSet = false, }; parentInterfaceContainer.Members.Add(member); AddMemberComment(member, summary); } else { var paramNames = node.FormatStringValue.Arguments.Select(a => Helper.Refine(a.Name)).ToArray(); var param = paramNames.Select(a => new CodeParameterDeclarationExpression(Statics.Object, a)).ToArray(); if (node.FormatStringValue.Arguments.Count != 0) { var getmethod = new CodeMemberMethod { Name = node.MemberName, ReturnType = Statics.FormattableResource, }; AddMemberComment(getmethod, summary); parentInterfaceContainer.Members.Add(getmethod); } var formatmethod = new CodeMemberMethod { Name = node.MemberName, ReturnType = Statics.String, }; formatmethod.Parameters.AddRange(param); AddMemberComment(formatmethod, summary); parentInterfaceContainer.Members.Add(formatmethod); var provider = Helper.GetUnusedName(paramNames, Strings.ProviderNames); if (provider != null) { var formatmethodfull = new CodeMemberMethod { Name = node.MemberName, ReturnType = Statics.String, Parameters = { new CodeParameterDeclarationExpression(Statics.IFormatProvider, provider) } }; formatmethodfull.Parameters.AddRange(param); AddMemberComment(formatmethodfull, summary); parentInterfaceContainer.Members.Add(formatmethodfull); } } }
public void RanmeItemPropertyParameters_default_to_null() { // ARRANGE var node = new LeafNode("name", ServiceProvider()); // ACT var result = node.RenameItemPropertyParameters("propertyName", "newPropertyName"); // ASSERT Assert.Null(result); }
public static LeafNode FormLinkedListFromLeaves(TreeNode root) { if (root == null) { return(null); } var dummyHead = new LeafNode(-1); LeavesHelper(root, dummyHead); return(dummyHead.next); }
public void Invoke_GetItemProperty_at_PSObject_ignores_unkown_properties() { // ARRANGE var node = new LeafNode("name", new GetItemPropertyData()); // ACT var result = node.GetItemProperty(new[] { "property", "unknown" }); // ASSERT Assert.Equal(1, result.Properties.Single().Value); }
public void Invoke_GetItemPropertyParameters_defaults_to_null() { // ARRANGE var node = new LeafNode("name", ServiceProvider()); // ACT var result = node.GetItemPropertyParameters(new[] { "property" }); // ASSERT Assert.Null(result); }
/// <summary> /// Adds a type of <see cref="LeafNode"/> with a sub-behaviour engine in it and its transition to the entry state /// </summary> /// <param name="stateName">The name of the state</param> /// <param name="subBehaviourTree">The sub-behaviour tree inside the </param> public LeafNode CreateSubBehaviour(string nodeName, BehaviourEngine subBehaviourEngine) { State stateTo = subBehaviourEngine.GetEntryState(); State state = new State(nodeName, subBehaviourEngine.GetState("Entry_Machine"), stateTo, subBehaviourEngine, this); LeafNode leafNode = new LeafNode("Node to return", state, this); subBehaviourEngine.NodeToReturn = leafNode; states.Add(leafNode.StateNode.Name, leafNode.StateNode); return(subBehaviourEngine.NodeToReturn); }
/// <summary> /// Perform diagnostics check for data structure internal errors. Since this is an /// in-memory managed structure, any errors would indicate a bug. Also performs space /// complexity diagnostics to ensure that all non-rightmost nodes maintain 50% fill. /// </summary> /// </exclude> public void SanityCheck() { int Order = root.KeyCapacity + 1; LeafNode lastLeaf = Check(root, 1, true, default(TKey), null); if (lastLeaf.RightLeaf != null) { throw new BPlusTreeInsaneException("Last leaf has invalid RightLeaf"); } }
public void WriteValue(ExcelRange cell, IClusterableMatch match, LeafNode leafNode) { if (!string.IsNullOrWhiteSpace(match.Match.TreeUrl)) { cell.StyleName = "HyperLink"; cell.Hyperlink = new ExcelHyperLink(match.Match.TreeUrl, UriKind.Absolute) { Display = "Tree" }; } }
private void setMeshes(IntermediateNode vMeshLibrary, ILibFile materialLibrary) { foreach (IntermediateNode vmsNode in vMeshLibrary) { if (vmsNode.Count != 1) { throw new Exception("Invalid VMeshLibrary: More than one child or zero elements: " + vmsNode.Name); } LeafNode vMeshDataNode = vmsNode[0] as LeafNode; Meshes.Add(CrcTool.FLModelCrc(vmsNode.Name), new VMeshData(vMeshDataNode.ByteArrayData, materialLibrary, vmsNode.Name)); } }
internal void InternalReset() { if (_list._version != _version) { throw new InvalidOperationException(); } _leafNode = null; _index = -1; _leafIndex = -1; _current = default; }
public void Reset() { if (_builder != null && _builder.Version != _version) { throw new InvalidOperationException(); } _leafNode = null; _index = -1; _leafIndex = -1; _current = default; }
public void MoveItemProperty_defaults_to_exception() { // ARRANGE var sourceNode = new LeafNode("name", ServiceProvider()); var destinationNode = new LeafNode("name", ServiceProvider()); // ACT var result = Assert.Throws <PSNotSupportedException>(() => destinationNode.MoveItemProperty(sourceNode, "sourceProperty", "destinationProperty")); // ASSERT Assert.Equal($"Node(name='name') doesn't provide an implementation of capability 'IMoveItemProperty'.", result.Message); }
public void AddChild (LeafNode LNode) { GameObject go = treeVis.InstanceNodeGameobject (LNode.Name); NodeVis nv = go.AddComponent<NodeVis> (); go.transform.parent = this.transform; go.transform.localScale = Vector3.one; go.layer = this.gameObject.layer; nv.parent = this; nv.treeVis = treeVis; nv.init (LNode); childs.Add (nv); NeedSizeRecalced = true; }
public void Test_InnerNode_Redistribute() { var child = new InnerNode<int, int>(4); var sibling = new InnerNode<int, int>(4); child.Keys.Add(1); var childLeaf = new LeafNode<int, int>(4); childLeaf.Keys.Add(1); childLeaf.Values.Add(new List<int>()); childLeaf.Values[0].Add(1); child.Children.Add(childLeaf); sibling.Keys.Add(2); var siblingChild1 = new LeafNode<int, int>(4); siblingChild1.Keys.Add(2); siblingChild1.Values.Add(new List<int>()); siblingChild1.Values[0].Add(2); siblingChild1.Keys.Add(3); siblingChild1.Values.Add(new List<int>()); siblingChild1.Values[1].Add(3); sibling.Children.Add(siblingChild1); sibling.Keys.Add(4); var siblingChild2 = new LeafNode<int, int>(4); siblingChild2.Keys.Add(4); siblingChild2.Values.Add(new List<int>()); siblingChild2.Values[0].Add(4); siblingChild2.Keys.Add(5); siblingChild2.Values.Add(new List<int>()); siblingChild2.Values[1].Add(5); sibling.Children.Add(siblingChild2); sibling.Keys.Add(6); var siblingChild3 = new LeafNode<int, int>(4); siblingChild3.Keys.Add(6); siblingChild3.Values.Add(new List<int>()); siblingChild3.Values[0].Add(6); siblingChild3.Keys.Add(7); siblingChild3.Values.Add(new List<int>()); siblingChild3.Values[1].Add(7); sibling.Children.Add(siblingChild3); child.Redistribute(sibling, -1); Assert.AreEqual(2, sibling.Children.Count); Assert.AreEqual(2, sibling.Keys.Count); Assert.AreEqual(2, child.Keys.Count); Assert.AreEqual(2, child.Children.Count); }
public void AddOnLeafShouldCreateBranchIfKeysAreDifferent () { var leaf = new LeafNode<string> (5, "hello"); //101 var branch = (BranchNode<string>) leaf.Add (7, "there"); //111 Assert.That (branch.Prefix, Is.EqualTo (1)); //x*1 Assert.That (branch.BranchingBit, Is.EqualTo (2)); // Assert.That (branch.Left, Is.SameAs (leaf)); var right = (branch.Right as LeafNode<string>); Assert.That (right, Is.Not.Null); Assert.That (right.Key, Is.EqualTo (7)); Assert.That (right.Value, Is.EqualTo ("there")); }
private static void FirstWalk(LeafNode currentNode, int currentLevel) { currentNode.LeftSibling = GetPrevNodeAtLevel( currentLevel ); SetPrevNodeAtLevel( currentLevel, currentNode ); currentNode.Modifier = 0; if( currentNode.IsLeaf() || (currentLevel == MaxLevelDepth) ) { if( currentNode.HasLeftSibling() ) { currentNode.PreliminaryLocation = currentNode.GetLeftSibling().PreliminaryLocation + HorizontalSiblingSeparationFine + CalcAverageNodeSize( currentNode.GetLeftSibling(), currentNode ); } else { currentNode.PreliminaryLocation = 0; } } else { var rightMostNode = currentNode.GetFirstChild(); var leftMostNode = rightMostNode; FirstWalk( leftMostNode, currentLevel + 1 ); while ( rightMostNode.HasRightSibling() ) { rightMostNode = rightMostNode.GetRightSibling(); FirstWalk( rightMostNode, currentLevel + 1 ); } var midpoint = (leftMostNode.PreliminaryLocation + rightMostNode.PreliminaryLocation) / 2; if( currentNode.HasLeftSibling() ) { currentNode.PreliminaryLocation = currentNode.GetLeftSibling().PreliminaryLocation + HorizontalSiblingSeparationFine + CalcAverageNodeSize( currentNode.GetLeftSibling(), currentNode ); currentNode.Modifier = currentNode.PreliminaryLocation - midpoint; Apportion( currentNode, currentLevel ); } else { currentNode.PreliminaryLocation = midpoint; } } }
public void Test_LeafNode_Split() { var node = new LeafNode<int, int>(3); for (int i = 1; i <= 3; i++) { node.Keys.Add(i); node.Values.Add(new List<int>()); node.Values[0].Add(1); } var split = node.Split() as LeafNode<int, int>; Assert.IsNotNull(split); Assert.AreEqual(1, node.Keys.Count); Assert.AreEqual(1, node.Values.Count); Assert.AreEqual(2, split.Keys.Count); Assert.AreEqual(2, split.Values.Count); Assert.AreSame(node.Next, split); }
public void Test_LeafNode_Redistribute_Left() { var child = new LeafNode<int, int>(4); var sibling = new LeafNode<int, int>(4); for (int i = 1; i <= 4; i++) { var node = sibling; if (i <= 1) node = child; node.Keys.Add(i); node.Values.Add(new List<int>()); node.Values[0].Add(i); } child.Redistribute(sibling, -1); Assert.AreEqual(2, child.Keys.Count); Assert.AreEqual(2, sibling.Keys.Count); }
public void Test_LeafNode_Merge() { var left = new LeafNode<int, int>(3); left.Keys.Add(1); left.Values.Add(new List<int>()); left.Values[0].Add(1); left.Keys.Add(2); left.Values.Add(new List<int>()); left.Values[1].Add(2); var right = new LeafNode<int, int>(3); right.Keys.Add(3); right.Values.Add(new List<int>()); right.Values[0].Add(3); left.Merge(right); Assert.AreEqual(0, right.Keys.Count); Assert.AreEqual(0, right.Values.Count); Assert.AreEqual(3, left.Keys.Count); Assert.AreEqual(3, left.Values.Count); }
public void SetProgram(List<Loop> loops, List<BasicBlock> blocks) { // build DAG of basic blocks // excluding backedges Graph g = new Graph(); Dictionary<BasicBlock, Node> NodeMap = new Dictionary<BasicBlock, Node>(); foreach (BasicBlock b in blocks) { Node n = new LeafNode(b); g.AddNode(n); NodeMap.Add(b,n); } foreach (BasicBlock b in blocks) foreach (BasicBlock s in b.Successors) if (!s.Dominates(b)) g.AddEdge(NodeMap[b], NodeMap[s]); // walk over loops inner to outer // for each loop, replace its contents with a single "super-node" foreach( Loop l in loops ) { Node[] loopNodes = new Node[l.BlockCount]; int n = 0; foreach (BasicBlock b in l.Blocks) loopNodes[n++] = NodeMap[b]; LoopNode superNode = new LoopNode(new Graph(), l); g.CombineNodes(loopNodes,superNode,superNode.SubGraph ); } BuildBranchNodes(g); // now populate the tree view with loops and branches TreeNode root = new TreeNode("program"); BuildTree(root, g); treeView1.Nodes.Add(root); }
/// <summary> /// This function determines the coordinates for each /// node in a tree. A pointer to the apex node of the /// tree is passed as input. This assumes that the x /// and y coordinates of the apex node are set as /// desired, since the tree underneath it will be /// positioned with respect to those coordinates. /// </summary> /// <param name="apexNode">The root node of the tree to be positioned</param> /// <returns>TRUE if no errors, otherwise returns FALSE</returns> public static bool PositionTree(LeafNode apexNode) { if( apexNode == null ) return true; InitListofPreviousNodes(); // Do the preliminary positioning with postorder walk. FirstWalk( apexNode, 0 ); // Determine how to adjust all the nodes with respect to // the location of the root. _xTopAdjustment = apexNode.HorizontalCoordinate - (int) apexNode.PreliminaryLocation; _yTopAdjustment = apexNode.VerticalCoordinate; // Do the final positioning with a preorder walk. var result = SecondWalk( apexNode, 0, 0 ); if( result ) { apexNode.ExecuteCallback(); } return result; }
public Node ProcessElement(XmlElement startEl) { if (IsComplex(startEl)) { CompositeNode top = new CompositeNode(startEl.LocalName); foreach(XmlAttribute attr in startEl.Attributes) { LeafNode leaf = new LeafNode(typeof(String), attr.LocalName, attr.Value); top.AddChildNode(leaf); } foreach(XmlElement childEl in startEl.ChildNodes) { Node childNode = ProcessElement(childEl); top.AddChildNode(childNode); } return top; } else { LeafNode top = new LeafNode(typeof(String), "", ""); return top; } }
public InnerNode(int key) { Key = key; Left = new LeafNode(); Right = new LeafNode(); }
private static LeafNode GetLeftMost(LeafNode currentNode, int currentLevel, int searchDepth) { if( currentLevel == searchDepth ) return currentNode; if( currentNode.IsLeaf() ) return null; var rightMostNode = currentNode.GetFirstChild(); var leftMost = GetLeftMost( rightMostNode, currentLevel + 1, searchDepth ); while ( leftMost == null && rightMostNode.HasRightSibling() ) { leftMost = GetLeftMost( rightMostNode, currentLevel + 1, searchDepth ); rightMostNode = rightMostNode.GetRightSibling(); } return leftMost; }
private static float CalcAverageNodeSize(LeafNode leftNode, LeafNode rightNode) { float nodeSize = 0; if( leftNode != null ) { nodeSize += (float) leftNode.Width / 2; } if( rightNode != null ) { nodeSize += (float) rightNode.Width / 2; } return nodeSize; }
private static void SetPrevNodeAtLevel(int levelNumber, LeafNode thisNode) { uint i = 0; for ( var tmp = _levelZeroPointer; tmp != null; tmp = tmp.NextLevel ) { if( i++ == levelNumber ) { tmp.PrevNode = thisNode; return; } if( tmp.NextLevel == null ) { tmp.NextLevel = new PreviousNode { PrevNode = null, NextLevel = null }; } } _levelZeroPointer = new PreviousNode { PrevNode = thisNode, NextLevel = null }; }
public INode assoc(int shift, int hash, object key, object val, Box addedLeaf) { int bit = bitpos(hash, shift); int idx = index(bit); if ((_bitmap & bit) != 0) { INode n = _nodes[idx].assoc(shift + 5, hash, key, val, addedLeaf); if (n == _nodes[idx]) return this; else { INode[] newnodes = (INode[])_nodes.Clone(); newnodes[idx] = n; return new BitmapIndexedNode(_bitmap, newnodes, shift); } } else { INode[] newnodes = new INode[_nodes.Length + 1]; Array.Copy(_nodes, 0, newnodes, 0, idx); addedLeaf.Val = newnodes[idx] = new LeafNode(hash, key, val); Array.Copy(_nodes, idx, newnodes, idx + 1, _nodes.Length - idx); return create(_bitmap | bit, newnodes, shift); } }
public INode assoc(int shift, int hash, object key, object val, Box addedLeaf) { INode ret = new LeafNode(hash, key, val); addedLeaf.Val = ret; return ret; }
internal abstract bool TryToInsert(LeafNode node, out Node treeNode);
public INode without(int hash, object key) { int idx = findIndex(hash, key); if (idx == -1) return this; if (_leaves.Length == 2) return idx == 0 ? _leaves[1] : _leaves[0]; LeafNode[] newLeaves = new LeafNode[_leaves.Length - 1]; Array.Copy(_leaves, 0, newLeaves, 0, idx); Array.Copy(_leaves, idx + 1, newLeaves, idx, _leaves.Length - (idx + 1)); return new HashCollisionNode(hash, newLeaves); }
public INode assoc(int shift, int hash, object key, object val, Box addedLeaf) { if (hash == _hash) { if (Util.equals(key, _key)) { if (val == _val) return this; // note - do not set AddedLeaf, since we are replacing else return new LeafNode(hash, key, val); } else { // hash collision, same hash, different keys LeafNode newLeaf = new LeafNode(hash, key, val); addedLeaf.Val = newLeaf; return new HashCollisionNode(hash, this, newLeaf); } } else return BitmapIndexedNode.create(shift, this, hash, key, val, addedLeaf); }
internal override bool TryToInsert(LeafNode node, out Node treeNode) { ////The following can make the tree shorter, but it actually hurt query times in testing. //bool aIsLeaf = childA.IsLeaf; //bool bIsLeaf = childB.IsLeaf; //if (aIsLeaf && !bIsLeaf) //{ // //Just put us with the leaf. Keeps the tree shallower. // BoundingBox merged; // BoundingBox.CreateMerged(ref childA.BoundingBox, ref node.BoundingBox, out merged); // childA = new InternalNode() { BoundingBox = merged, childA = this.childA, childB = node }; // treeNode = null; // return true; //} //else if (!aIsLeaf && bIsLeaf) //{ // //Just put us with the leaf. Keeps the tree shallower. // BoundingBox merged; // BoundingBox.CreateMerged(ref childB.BoundingBox, ref node.BoundingBox, out merged); // childB = new InternalNode() { BoundingBox = merged, childA = node, childB = this.childB }; // treeNode = null; // return true; //} //Since we are an internal node, we know we have two children. //Regardless of what kind of nodes they are, figure out which would be a better choice to merge the new node with. //Use the path which produces the smallest 'volume.' BoundingBox mergedA, mergedB; BoundingBox.CreateMerged(ref ChildA.BoundingBox, ref node.BoundingBox, out mergedA); BoundingBox.CreateMerged(ref ChildB.BoundingBox, ref node.BoundingBox, out mergedB); Vector3 offset; float originalAVolume, originalBVolume; Vector3.Subtract(ref ChildA.BoundingBox.Max, ref ChildA.BoundingBox.Min, out offset); originalAVolume = offset.X * offset.Y * offset.Z; Vector3.Subtract(ref ChildB.BoundingBox.Max, ref ChildB.BoundingBox.Min, out offset); originalBVolume = offset.X * offset.Y * offset.Z; float mergedAVolume, mergedBVolume; Vector3.Subtract(ref mergedA.Max, ref mergedA.Min, out offset); mergedAVolume = offset.X * offset.Y * offset.Z; Vector3.Subtract(ref mergedB.Max, ref mergedB.Min, out offset); mergedBVolume = offset.X * offset.Y * offset.Z; //Could use factor increase or absolute difference if (mergedAVolume - originalAVolume < mergedBVolume - originalBVolume) { //merging A produces a better result. if (ChildA.IsLeaf) { ChildA = new InternalNode() { BoundingBox = mergedA, ChildA = this.ChildA, ChildB = node }; treeNode = null; return true; } else { ChildA.BoundingBox = mergedA; treeNode = ChildA; return false; } } else { //merging B produces a better result. if (ChildB.IsLeaf) { //Target is a leaf! Return. ChildB = new InternalNode() { BoundingBox = mergedB, ChildA = node, ChildB = this.ChildB }; treeNode = null; return true; } else { ChildB.BoundingBox = mergedB; treeNode = ChildB; return false; } } }
public void Test_InnerNode_Split_Test() { var innerNode = new InnerNode<int, int>(3); var leafNode = new LeafNode<int, int>(3); leafNode.Keys.Add(1); leafNode.Values.Add(new List<int>()); leafNode.Values[0].Add(1); innerNode.Children.Add(leafNode); innerNode.Keys.Add(2); leafNode = new LeafNode<int, int>(3); leafNode.Keys.Add(2); leafNode.Values.Add(new List<int>()); leafNode.Values[0].Add(2); innerNode.Children.Add(leafNode); innerNode.Keys.Add(3); leafNode = new LeafNode<int, int>(3); leafNode.Keys.Add(3); leafNode.Values.Add(new List<int>()); leafNode.Values[0].Add(3); innerNode.Children.Add(leafNode); innerNode.Keys.Add(4); leafNode = new LeafNode<int, int>(3); leafNode.Keys.Add(4); leafNode.Values.Add(new List<int>()); leafNode.Values[0].Add(4); leafNode.Keys.Add(5); leafNode.Values.Add(new List<int>()); leafNode.Values[1].Add(5); innerNode.Children.Add(leafNode); var split = innerNode.Split() as InnerNode<int, int>; Assert.IsNotNull(split); Assert.AreEqual(2, innerNode.Children.Count); Assert.AreEqual(2, innerNode.Keys.Count); Assert.AreEqual(2, split.Children.Count); // this key will get promoted Assert.AreEqual(1, split.Keys.Count); }
public void Test_Tree_Delete() { var root = new InnerNode<int, int>(3); root.Keys.Add(15); var level1Child1 = new InnerNode<int, int>(3); level1Child1.Keys.Add(9); level1Child1.Keys.Add(12); var level2Child1 = new LeafNode<int, int>(3); level2Child1.Add(1, 1); level2Child1.Add(4, 4); level1Child1.Children.Add(level2Child1); var level2Child2 = new LeafNode<int, int>(3); level2Child2.Add(9, 9); level2Child2.Add(10, 10); level1Child1.Children.Add(level2Child2); var level2Child3 = new LeafNode<int, int>(3); level2Child3.Add(12, 12); level2Child3.Add(13, 13); level1Child1.Children.Add(level2Child3); root.Children.Add(level1Child1); var level1Child2 = new InnerNode<int, int>(3); level1Child2.Keys.Add(20); var level2Child4 = new LeafNode<int, int>(3); level2Child4.Add(15, 15); level2Child4.Add(16, 16); level1Child2.Children.Add(level2Child4); var level2Child5 = new LeafNode<int, int>(3); level2Child5.Add(20,20); level2Child5.Add(25,25); level1Child2.Children.Add(level2Child5); root.Children.Add(level1Child2); var tree = new Tree<int, int>(root); tree.Delete(13); Assert.AreEqual(1, root.Keys.Count); Assert.AreEqual(15, root.Keys[0]); var delete13Parent = (root.Children[0] as InnerNode<int, int>); Assert.AreEqual(2, delete13Parent.Keys.Count); Assert.AreEqual(09, delete13Parent.Keys[0]); Assert.AreEqual(12, delete13Parent.Keys[1]); Assert.AreEqual(3, delete13Parent.Children.Count); var delete13Child3 = delete13Parent.Children[2]; Assert.AreEqual(1, delete13Child3.Keys.Count); Assert.AreEqual(12, delete13Child3.Keys[0]); tree.Delete(15); var delete15Parent = (root.Children[1] as InnerNode<int, int>); Assert.AreEqual(1, delete15Parent.Keys.Count); Assert.AreEqual(20, delete15Parent.Keys[0]); Assert.AreEqual(2, delete15Parent.Children.Count); var delete15Child1 = delete15Parent.Children[0]; Assert.AreEqual(1, delete15Child1.Keys.Count); Assert.AreEqual(16, delete15Child1.Keys[0]); tree.Delete(12); var delete12Parent = (root.Children[0] as InnerNode<int, int>); Assert.AreEqual(2, delete12Parent.Keys.Count); Assert.AreEqual(9, delete12Parent.Keys[0]); Assert.AreEqual(10, delete12Parent.Keys[1]); Assert.AreEqual(3, delete12Parent.Children.Count); var delete12Child2 = delete12Parent.Children[1]; Assert.AreEqual(1, delete12Child2.Keys.Count); Assert.AreEqual(9, delete12Child2.Keys[0]); var delete12Child3 = delete12Parent.Children[2]; Assert.AreEqual(1, delete12Child3.Keys.Count); Assert.AreEqual(10, delete12Child3.Keys[0]); tree.Delete(16); var delete16Parent = (root.Children[1] as InnerNode<int, int>); Assert.AreEqual(2, delete16Parent.Children.Count); Assert.AreEqual(1, delete16Parent.Keys.Count); Assert.AreEqual(25, delete16Parent.Keys[0]); var delete16Child1 = delete16Parent.Children[0]; Assert.AreEqual(1, delete16Child1.Keys.Count); Assert.AreEqual(20, delete16Child1.Keys[0]); var delete16Child2 = delete16Parent.Children[1]; Assert.AreEqual(1, delete16Child2.Keys.Count); Assert.AreEqual(25, delete16Child2.Keys[0]); tree.Delete(25); tree.Delete(10); }
void Insert(int triangleIndex) { //Insertions can easily be performed stacklessly. //Only one path is chosen at each step and nothing is returned, so the history of the 'recursion' is completely forgotten. var node = new LeafNode(triangleIndex, data); if (root == null) { //Empty tree. This is the first and only node. root = node; } else { if (root.IsLeaf) //Root is alone. root.TryToInsert(node, out root); else { //The caller is responsible for the merge. BoundingBox.CreateMerged(ref node.BoundingBox, ref root.BoundingBox, out root.BoundingBox); Node treeNode = root; while (!treeNode.TryToInsert(node, out treeNode)) ;//TryToInsert returns the next node, if any, and updates node bounding box. } } }
public INode assoc(int shift, int hash, object key, object val, Box addedLeaf) { if (_hash == hash) { int idx = findIndex(hash, key); if (idx != -1) { if (_leaves[idx].val() == val) return this; LeafNode[] newLeaves1 = (LeafNode[])_leaves.Clone(); // Note: do not set addedLeaf, since we are replacing newLeaves1[idx] = new LeafNode(hash, key, val); return new HashCollisionNode(hash, newLeaves1); } LeafNode[] newLeaves = new LeafNode[_leaves.Length + 1]; Array.Copy(_leaves, 0, newLeaves, 0, _leaves.Length); addedLeaf.Val = newLeaves[_leaves.Length] = new LeafNode(hash, key, val); return new HashCollisionNode(hash, newLeaves); } return BitmapIndexedNode.create(shift, this, hash, key, val, addedLeaf); }
internal override bool TryToInsert(LeafNode node, out Node treeNode) { var newTreeNode = new InternalNode(); BoundingBox.CreateMerged(ref BoundingBox, ref node.BoundingBox, out newTreeNode.BoundingBox); newTreeNode.ChildA = this; newTreeNode.ChildB = node; treeNode = newTreeNode; return true; }