示例#1
0
        public void RotationTests()
        {
            var tree = new RedBlackTree<Int32>();

            tree.Insert(35);
            tree.Insert(25);
            tree.Insert(70);
            tree.Insert(10);
            tree.Insert(100);
            tree.Insert(20);
            tree.Insert(5);
            tree.Insert(85);
            tree.Insert(55);
            tree.Insert(40);

            Assert.AreEqual(35, tree.RootNode.NodeValue);
            Assert.AreEqual(20, tree.RootNode.LeftNode.NodeValue);
            Assert.AreEqual(25, tree.RootNode.LeftNode.RightNode.NodeValue);
            Assert.AreEqual(10, tree.RootNode.LeftNode.LeftNode.NodeValue);
            Assert.AreEqual(5, tree.RootNode.LeftNode.LeftNode.LeftNode.NodeValue);

            Assert.AreEqual(85, tree.RootNode.RightNode.NodeValue);
            Assert.AreEqual(100, tree.RootNode.RightNode.RightNode.NodeValue);
            Assert.AreEqual(55, tree.RootNode.RightNode.LeftNode.NodeValue);
            Assert.AreEqual(40, tree.RootNode.RightNode.LeftNode.LeftNode.NodeValue);
            Assert.AreEqual(70, tree.RootNode.RightNode.LeftNode.RightNode.NodeValue);
        }
示例#2
0
        private static int BuildStorageEntry(DirectoryEntry storageEntry)
        {
            // direct members of each storage are organised in a separate red-black tree
            RedBlackTree<DirectoryEntry> rbTree = new RedBlackTree<DirectoryEntry>();
            foreach (DirectoryEntry entry in storageEntry.Members.Values)
            {
                rbTree.Add(entry);
            }

            foreach (RedBlackTreeNode<DirectoryEntry> node in rbTree.InorderTreeWalk(rbTree.Root))
            {
                DirectoryEntry entry = node.Data;
                entry.NodeColor = GetNodeColor(node.Color);
                entry.LeftChildDID = GetNodeID(node.Left);
                entry.RightChildDID = GetNodeID(node.Right);

                if (entry.Members.Count > 0)
                {
                    entry.EntryType = EntryType.Storage;
                    entry.MembersTreeNodeDID = BuildStorageEntry(entry);
                }
                else
                {
                    entry.EntryType = EntryType.Stream;
                    entry.MembersTreeNodeDID = -1;
                }
            }

            return rbTree.Root.Data.ID;
        }
示例#3
0
        public void NonIComparable()
        {
            var redBlackTree = new RedBlackTree<NonComparableTClass, string>();

            for (var i = 0; i < 100; i++)
            {
                redBlackTree.Add(new NonComparableTClass(i), i.ToString());
            }

            var newTree = SerializeUtil.BinarySerializeDeserialize(redBlackTree);

            Assert.AreNotSame(redBlackTree, newTree);
            Assert.AreEqual(redBlackTree.Count, newTree.Count);

            var redBlackTreeEnumerator = redBlackTree.GetEnumerator();
            var newTreeEnumerator = newTree.GetEnumerator();

            while (redBlackTreeEnumerator.MoveNext())
            {
                Assert.IsTrue(newTreeEnumerator.MoveNext());
                Assert.AreEqual(redBlackTreeEnumerator.Current.Key.Number, newTreeEnumerator.Current.Key.Number);
                Assert.AreEqual(redBlackTreeEnumerator.Current.Value, newTreeEnumerator.Current.Value);

                Assert.IsTrue(newTree.ContainsKey(redBlackTreeEnumerator.Current.Key));
                Assert.AreEqual(newTree[redBlackTreeEnumerator.Current.Key], redBlackTreeEnumerator.Current.Value);
            }

            Assert.IsFalse(newTreeEnumerator.MoveNext());
        }
示例#4
0
        public void EmptyTreeTest()
        {
            var tree = new RedBlackTree<Int32>();

            Assert.IsTrue(tree.IsEmpty);
            Assert.IsFalse(tree.BredthContains(2));
        }
示例#5
0
文件: Add.cs 项目: GTuritto/ngenerics
 public void ExceptionNullKey()
 {
     var redBlackTree = new RedBlackTree<object, string>
                            {
                                {null, "a"}
                            };
 }
        public void AddExample()
        {
            // Create a simple tree
            var tree = new RedBlackTree<string, int> {{"cat", 1}, {"dog", 2}, {"canary", 3}};

            // There should be 3 items in the tree.
            Assert.AreEqual(3, tree.Count);
        }
示例#7
0
文件: Add.cs 项目: GTuritto/ngenerics
 public void ExceptionKeyAlreadyInTree()
 {
     var redBlackTree = new RedBlackTree<int, string>
                            {
                                {0, "50"},
                                {0, "20"}
                            };
 }
示例#8
0
        public void RootNodeTest()
        {
            var tree = new RedBlackTree<Int32>();
            tree.Insert(10);

            Assert.IsFalse(tree.IsEmpty);
            Assert.IsTrue(tree.BredthContains(10));
            Assert.AreEqual(10, tree.RootNode.NodeValue);
        }
示例#9
0
        public void ContainsSuccessTest()
        {
            var tree = new RedBlackTree<Int32>();

            tree.Insert(10);
            tree.Insert(25);
            tree.Insert(7);

            Assert.IsTrue(tree.BredthContains(25));
        }
示例#10
0
        public void Simple()
        {
            var redBlackTree = new RedBlackTree<int, string>();
            Assert.AreEqual(redBlackTree.Count, 0);
            Assert.IsTrue(redBlackTree.Comparer is KeyValuePairComparer<int, string>);

            redBlackTree = new RedBlackTree<int, string>(new ReverseComparer<int>());
            Assert.AreEqual(redBlackTree.Count, 0);
            Assert.IsTrue(redBlackTree.Comparer.GetType().IsAssignableFrom(typeof(KeyValuePairComparer<int, string>)));
        }
示例#11
0
        public void ContainsFailureTest()
        {
            var tree = new RedBlackTree<Int32>();

            tree.Insert(10);
            tree.Insert(25);
            tree.Insert(7);

            Assert.IsFalse(tree.BredthContains(2));
        }
        public void AddItem()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            int temp;

            tree.Add(1, 1);

            Assert.AreEqual(tree.Count, 1);
            Assert.IsTrue(tree.TryGetValue(1, out temp));
            Assert.IsFalse(tree.TryGetValue(2, out temp));
        }
示例#13
0
文件: Count.cs 项目: havok/ngenerics
        public void Simple()
        {
            var redBlackTree = GetTestTree();
            Assert.IsFalse(redBlackTree.IsEmpty);

            redBlackTree.Clear();
            Assert.IsTrue(redBlackTree.IsEmpty);

            redBlackTree = new RedBlackTree<int, string>();
            Assert.IsTrue(redBlackTree.IsEmpty);
        }
示例#14
0
        internal static RedBlackTree<int, string> GetTestTree(int noOfItems)
        {
            var redBlackTree = new RedBlackTree<int, string>();

            for (var i = 0; i < noOfItems; i++)
            {
                redBlackTree.Add(i, i.ToString());
            }

            return redBlackTree;
        }
示例#15
0
        public void AddTest()
        {
            //Arrange
            var bst = new RedBlackTree<int, string>();

            // 33 28 63 20 31 39 79 10 35 60          ( red links = 10 39 )

            var testData = new[]
            {
                new KeyValuePair<int, string>(33, "33"),
                new KeyValuePair<int, string>(28, "28"),
                new KeyValuePair<int, string>(63, "63"),
                new KeyValuePair<int, string>(20, "20"),
                new KeyValuePair<int, string>(31, "31"),
                new KeyValuePair<int, string>(39, "39"),
                new KeyValuePair<int, string>(79, "79"),
                new KeyValuePair<int, string>(10, "10"),
                new KeyValuePair<int, string>(35, "35"),
                new KeyValuePair<int, string>(60, "60"),
            };

            //Act
            Array.ForEach(testData, t =>
            {
                bst.Add(t.Key, t.Value);
            });

            bst.Add(75, "75");
            bst.Add(38, "38");
            bst.Add(12, "12");

            var result = bst.LevelOrderTraversal();

            //Assert
            Assert.AreEqual(result.ElementAt(0).Key, 33);
            Assert.AreEqual(result.ElementAt(1).Key, 28);
            Assert.AreEqual(result.ElementAt(2).Key, 63);
            Assert.AreEqual(result.ElementAt(3).Key, 12);
            Assert.AreEqual(result.ElementAt(4).Key, 31);
            Assert.AreEqual(result.ElementAt(5).Key, 39);
            Assert.AreEqual(result.ElementAt(6).Key, 79);
            Assert.AreEqual(result.ElementAt(7).Key, 10);
            Assert.AreEqual(result.ElementAt(8).Key, 20);
            Assert.AreEqual(result.ElementAt(9).Key, 38);
            Assert.AreEqual(result.ElementAt(10).Key, 60);
            Assert.AreEqual(result.ElementAt(11).Key, 75);
            Assert.AreEqual(result.ElementAt(12).Key, 35);

            //Assert are red nodes
            Assert.IsTrue(result.ElementAt(3).IsRed);
            Assert.IsTrue(result.ElementAt(5).IsRed);
            Assert.IsTrue(result.ElementAt(11).IsRed);
        }
示例#16
0
        public void LevelOrderTraversalTest()
        {
            //Arrange
            var bst = new RedBlackTree<int, string>();

            //70 40 81 13 57 75 85 10 32 48 66 82 43

            var testData = new[]
            {
                new KeyValuePair<int, string>(70, "70"),
                new KeyValuePair<int, string>(40, "40"),
                new KeyValuePair<int, string>(81, "81"),
                new KeyValuePair<int, string>(13, "13"),
                new KeyValuePair<int, string>(57, "57"),
                new KeyValuePair<int, string>(75, "75"),
                new KeyValuePair<int, string>(85, "85"),
                new KeyValuePair<int, string>(10, "10"),
                new KeyValuePair<int, string>(32, "32"),
                new KeyValuePair<int, string>(48, "48"),
                new KeyValuePair<int, string>(66, "66"),
                new KeyValuePair<int, string>(82, "82"),
                new KeyValuePair<int, string>(43, "43"),
            };

            //Act
            Array.ForEach(testData, t =>
            {
                bst.Add(t.Key, t.Value);
            });

            var result = bst.LevelOrderTraversal();

            //Assert
            Assert.AreEqual(result.ElementAt(0).Key, 70);
            Assert.AreEqual(result.ElementAt(1).Key, 40);
            Assert.AreEqual(result.ElementAt(2).Key, 81);
            Assert.AreEqual(result.ElementAt(3).Key, 13);
            Assert.AreEqual(result.ElementAt(4).Key, 57);
            Assert.AreEqual(result.ElementAt(5).Key, 75);
            Assert.AreEqual(result.ElementAt(6).Key, 85);
            Assert.AreEqual(result.ElementAt(7).Key, 10);
            Assert.AreEqual(result.ElementAt(8).Key, 32);
            Assert.AreEqual(result.ElementAt(9).Key, 48);
            Assert.AreEqual(result.ElementAt(10).Key, 66);
            Assert.AreEqual(result.ElementAt(11).Key, 82);
            Assert.AreEqual(result.ElementAt(12).Key, 43);

            //Assert are red nodes
            Assert.IsTrue(result.ElementAt(1).IsRed);
            Assert.IsTrue(result.ElementAt(12).IsRed);
            Assert.IsTrue(result.ElementAt(11).IsRed);
        }
示例#17
0
		public void TestRemoveBug ()
		{
			var tree = new RedBlackTree<TestNode> ();
			TestNode t1 = new TestNode (1);
			TestNode t2 = new TestNode (2);
			TestNode t3 = new TestNode (3);
			
			tree.Add (t1);
			tree.InsertRight (t1, t2);
			tree.InsertLeft (t1, t3);
			tree.Remove (t1);
			Assert.AreEqual (2, tree.Count);
		} 
        public void RemoveNonExistingItem()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(1, 1);
            int temp;

            
            bool removed = tree.Remove(2);

            Assert.IsFalse (removed);
            Assert.AreEqual(tree.Count, 1);
            Assert.IsTrue(tree.TryGetValue(1, out temp));
            Assert.IsFalse(tree.TryGetValue(2, out temp));
        }
示例#19
0
        static void Main(string[] args)
        {
            var stack = new Stack<string>();
            var tree = new RedBlackTree<string, string>();
            var dict = new Dictionary<string, string>();

            for (int i = 0; i < 1000000; i++)
            {
                stack.Push(Guid.NewGuid().ToString());
            }

            var sw = new Stopwatch();
            sw.Start();
            foreach (string item in stack)
            {
                tree.Add(item, item);
            }
            sw.Stop();
            System.Console.WriteLine("{0}", sw.Elapsed);

            sw.Reset();
            sw.Start();
            foreach (string item in stack)
            {
                dict.Add(item, item);
            }
            sw.Stop();
            System.Console.WriteLine("{0}", sw.Elapsed);

            sw.Reset();
            sw.Start();
            foreach (string item in stack)
            {
                tree.ContainsKey(item);
            }
            sw.Stop();
            System.Console.WriteLine("{0}", sw.Elapsed);

            sw.Reset();
            sw.Start();
            foreach (string item in stack)
            {
                dict.ContainsKey(item);
            }
            sw.Stop();
            System.Console.WriteLine("{0}", sw.Elapsed);

            System.Console.ReadKey();
        }
示例#20
0
        static void Main(string[] args)
        {
            var stack = new Stack<string>();
            var tree = new RedBlackTree<string, string>();

            for (int i = 0; i < 10000; i++)
            {
                stack.Push(Guid.NewGuid().ToString());
            }

            foreach (string item in stack)
            {
                tree.Add(item, item);
            }
        }
示例#21
0
			public long CalcOffset (RedBlackTree<TreeNode>.RedBlackTreeNode Node) 
			{
				RedBlackTree<TreeNode>.RedBlackTreeNode cur = Node;
				long offset = cur.left != null ? cur.left.value.TotalLength : 0;
				while (cur.parent != null) {
					if (cur == cur.parent.right) {
						if (cur.parent.left != null && cur.parent.left.value != null)
							offset += cur.parent.left.value.TotalLength;
						if (Node.parent.value != null)
							offset += cur.parent.value.Length;
					}
					cur = cur.parent;
				}
				return offset;
			}
示例#22
0
        public void AcceptVisitorExample()
        {
            var tree = new RedBlackTree<string, int> {{"cat", 1}, {"dog", 2}, {"canary", 3}};

            // There should be 3 items in the tree.
            Assert.AreEqual(3, tree.Count);

            // Create a visitor that will simply count the items in the tree.
            var visitor =
                new CountingVisitor<KeyValuePair<string, int>>();

            // Make the tree call IVisitor<T>.Visit on all items contained.
            tree.AcceptVisitor(visitor);

            // The counting visitor would have visited 3 items.
            Assert.AreEqual(3, visitor.Count);
        }
        public void CanEnumeratePairsOldSchool()
        {
            RedBlackTree <int, string> redBlackTree = new RedBlackTree <int, string>
            {
                { 1, "1" },
                { 2, "2" },
                { 3, "3" },
                { 4, "4" },
                { 5, "5" },
            };

            ICollection <KeyValuePair <int, string> > pairs = redBlackTree.KeyValuePairs;

            IEnumerator enumerator = ((IEnumerable)pairs).GetEnumerator();

            KeyValuePair <int, string>[] expectedPairs =
            {
                new KeyValuePair <int, string>(1, "1"),
                new KeyValuePair <int, string>(2, "2"),
                new KeyValuePair <int, string>(3, "3"),
                new KeyValuePair <int, string>(4, "4"),
                new KeyValuePair <int, string>(5, "5"),
            };

            int index = 0;

            while (enumerator.MoveNext())
            {
                Assert.That((KeyValuePair <int, string>)(enumerator.Current), Is.EqualTo(expectedPairs[index]));
                index++;
            }

            enumerator.Reset();

            index = 0;
            while (enumerator.MoveNext())
            {
                Assert.That((KeyValuePair <int, string>)(enumerator.Current), Is.EqualTo(expectedPairs[index]));
                index++;
            }
        }
示例#24
0
        public void AddCaseParentAndUncleRedRoot()
        {
            RedBlackTree <int, int> tree = new RedBlackTree <int, int>();

            tree.Add(2, 2);
            tree.Add(3, 3);
            tree.Add(1, 1);


            tree.Add(4, 4);

            //    B2
            // R1    R3
            //          R4
            //
            // parent and uncle red
            //
            //    B2
            // B1    B3
            //          R4

            var e2 = tree.RootElement;
            var e3 = e2.Right;
            var e1 = e2.Left;
            var e4 = e3.Right;

            AssertOrder(e1, e2, e3, e4);

            AssertRoot(e2);
            AssertParent(e4, e3);
            AssertParent(e3, e2);
            AssertParent(e1, e2);

            AssertLeaves(e1, e4);
            Assert.IsNull(e3.Left);

            Assert.IsTrue(!e1.Red);
            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(!e3.Red);
            Assert.IsTrue(e4.Red);
        }
示例#25
0
文件: Add.cs 项目: GTuritto/ngenerics
        public void Simple()
        {
            var redBlackTree = new RedBlackTree<int, string>();

            for (var i = 0; i < 100; i++)
            {
                redBlackTree.Add(i, i.ToString());

                Assert.IsTrue(redBlackTree.ContainsKey(i));
                Assert.AreEqual(redBlackTree.Count, i + 1);
            }

            for (var i = 300; i > 200; i--)
            {
                redBlackTree.Add(i, i.ToString());

                Assert.IsTrue(redBlackTree.ContainsKey(i));
                Assert.AreEqual(redBlackTree.Count, 100 + (300 - i) + 1);
            }

            for (var i = 100; i < 200; i++)
            {
                redBlackTree.Add(i, i.ToString());

                Assert.IsTrue(redBlackTree.ContainsKey(i));
                Assert.AreEqual(redBlackTree.Count, 100 + i + 1);
            }

            for (var i = 301; i < 400; i++)
            {
                redBlackTree.Add(new KeyValuePair<int, string>(i, i.ToString()));

                Assert.IsTrue(redBlackTree.ContainsKey(i));
                Assert.AreEqual(redBlackTree[i], i.ToString());
                Assert.IsTrue(redBlackTree.Contains(new KeyValuePair<int, string>(i, i.ToString())));
            }

            Assert.IsFalse(redBlackTree.Contains(new KeyValuePair<int, string>(500, "500")));
            Assert.IsFalse(redBlackTree.Contains(new KeyValuePair<int, string>(300, "301")));
            Assert.IsTrue(redBlackTree.Contains(new KeyValuePair<int, string>(300, "300")));
        }
        public void ShouldBeAbleToFindMinimaAndMaxima()
        {
            int seed = 12345;

            int RandomNext()
            {
                seed = (seed * 69069) + 12345;
                return((seed >> 16) & 0x7FFF);
            }

            RedBlackTree <int, int> tree = new RedBlackTree <int, int>();

            Assert.That(tree.MinimumKey, Is.EqualTo(default(int)));
            Assert.That(tree.MaximumKey, Is.EqualTo(default(int)));
            Assert.That(tree.MinimumNode, Is.Null);
            Assert.That(tree.MaximumNode, Is.Null);

            List <int> keys = new List <int>();

            for (int i = 0; i < 500; i++)
            {
                int key = RandomNext();
                keys.Add(key);

                tree.Add(key, i);

                int expectedMinimum = keys.Min();
                int actualMinimum   = tree.MinimumKey;
                Assert.That(expectedMinimum, Is.EqualTo(actualMinimum));

                RedBlackTreeNode <int, int> actualMinimumNode = tree.MinimumNode;
                Assert.That(expectedMinimum, Is.EqualTo(actualMinimumNode.Key));

                int expectedMaximum = keys.Max();
                int actualMaximum   = tree.MaximumKey;
                Assert.That(expectedMaximum, Is.EqualTo(actualMaximum));

                RedBlackTreeNode <int, int> actualMaximumNode = tree.MaximumNode;
                Assert.That(expectedMaximum, Is.EqualTo(actualMaximumNode.Key));
            }
        }
示例#27
0
        public void DuplicateTest()
        {
            var t = new RedBlackTree<int, string>();
            var collection = t as ICollection<KeyValuePair<int, string>>;

            var values = collection.ToArray();
            Assert.AreEqual(0, values.Length);

            t.Add(new KeyValuePair<int, string>(1, "1"));
            values = collection.ToArray();
            Assert.AreEqual(1, values.Length);

            t.Add(new KeyValuePair<int, string>(2, "2"));
            values = collection.ToArray();
            Assert.AreEqual(2, values.Length);
            Assert.AreEqual("1", values[0].Value);
            Assert.AreEqual("2", values[1].Value);


            t.Add(new KeyValuePair<int, string>(1, "bla"));
            values = collection.ToArray();
            Assert.AreEqual(2, values.Length);
            Assert.AreEqual("bla", values[0].Value);
            Assert.AreEqual("2", values[1].Value);

            var node1 = t.Remove(new KeyValuePair<int, string>(1, "-"));
            Assert.IsNotNull(node1);
            values = collection.ToArray();
            Assert.AreEqual(1, values.Length);
            Assert.AreEqual("2", values[0].Value);

            var node2 = t.Remove(new KeyValuePair<int, string>(1, "-"));
            Assert.IsNull(node2);
            values = collection.ToArray();
            Assert.AreEqual(1, values.Length);
            Assert.AreEqual("2", values[0].Value);

            var node3 = t.Remove(new KeyValuePair<int, string>(2, "-"));
            values = collection.ToArray();
            Assert.AreEqual(0, values.Length);
        }
        public void CanReadAsCollectionThroughAsDictionary()
        {
            RedBlackTree <int, string> tree = new RedBlackTree <int, string>
            {
                { 1, "1" },
                { 2, "2" },
                { 3, "3" },
                { 4, "4" },
                { 5, "5" },
            };

            IDictionary <int, string> dictionary = tree.AsDictionary();

            KeyValuePair <int, string>[] array = new KeyValuePair <int, string> [5];
            dictionary.CopyTo(array, 0);
            CollectionAssert.AreEquivalent(array, new[] {
                new KeyValuePair <int, string>(1, "1"),
                new KeyValuePair <int, string>(2, "2"),
                new KeyValuePair <int, string>(3, "3"),
                new KeyValuePair <int, string>(4, "4"),
                new KeyValuePair <int, string>(5, "5"),
            });

            CollectionAssert.AreEquivalent(dictionary.Keys, new[] { 1, 2, 3, 4, 5 });
            CollectionAssert.AreEquivalent(dictionary.Values, new[] { "1", "2", "3", "4", "5" });

            int index = 0;

            array = new KeyValuePair <int, string> [5];
            foreach (KeyValuePair <int, string> pair in dictionary)
            {
                array[index++] = pair;
            }
            CollectionAssert.AreEquivalent(array, new[] {
                new KeyValuePair <int, string>(1, "1"),
                new KeyValuePair <int, string>(2, "2"),
                new KeyValuePair <int, string>(3, "3"),
                new KeyValuePair <int, string>(4, "4"),
                new KeyValuePair <int, string>(5, "5"),
            });
        }
示例#29
0
        public void TestInterfaceGetEnumerator()
        {
            RedBlackTree <int, string>         tree = GetTestTree();
            List <KeyValuePair <int, string> > l    = new List <KeyValuePair <int, string> >();

            IEnumerator enumerator = ((IEnumerable)tree).GetEnumerator();

            {
                while (enumerator.MoveNext())
                {
                    l.Add((KeyValuePair <int, string>)enumerator.Current);
                }
            }

            Assert.AreEqual(l.Count, 100);

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(l.Contains(new KeyValuePair <int, string>(i, i.ToString())), true);
            }
        }
示例#30
0
        public void TryGetValueExample()
        {
            // Build a simple tree.
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            int value;

            // We'll get the value for cat successfully.
            Assert.IsTrue(tree.TryGetValue("cat", out value));

            // And the value should be 1.
            Assert.AreEqual(1, value);

            // But we won't get a horse
            Assert.IsFalse(tree.TryGetValue("horse", out value));
        }
        private static void TestNext(RedBlackTree <int, int> tree)
        {
            var node = tree.GetMinNode();

            Assert.IsFalse(tree.Terminal(node));
            var count = 1;

            while (true)
            {
                var next = tree.Next(node);
                if (tree.Terminal(next))
                {
                    break;
                }
                ++count;
                Assert.IsFalse(tree.Terminal(next));
                Assert.IsTrue(node.Key < next.Key);
                node = next;
            }
            Assert.AreEqual(tree.Count, count);
        }
示例#32
0
        public void RemoveExample()
        {
            // Build a simple tree.
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            // There are three items in the tree
            Assert.AreEqual(3, tree.Count);

            // Let's remove the dog
            tree.Remove("dog");

            // Now the tree contains only two items, and dog isn't
            // in the tree.
            Assert.AreEqual(2, tree.Count);
            Assert.IsFalse(tree.ContainsKey("dog"));
        }
示例#33
0
        public void ValuesExample()
        {
            // Build a simple tree.
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            // Retrieve the values from the tree.
            var values = tree.Values;

            // The keys collection contains three items :
            // 1, 2, and 3.
            Assert.AreEqual(3, values.Count);

            Assert.IsTrue(values.Contains(1));
            Assert.IsTrue(values.Contains(2));
            Assert.IsTrue(values.Contains(3));
        }
示例#34
0
        public void insert_three()
        {
            RedBlackTree <int, int> tree = new RedBlackTree <int, int>();

            tree.insert(1, 100);
            tree.insert(2, 99);
            tree.insert(3, 98);

            (bool missing, bool equal) = test_for_value(1, 100, tree);
            Assert.True(!missing);
            Assert.True(equal);


            (missing, equal) = test_for_value(2, 99, tree);
            Assert.True(!missing);
            Assert.True(equal);

            (missing, equal) = test_for_value(3, 98, tree);
            Assert.True(!missing);
            Assert.True(equal);
        }
        public void Delete_RightLeft_BlackNode_With_NoChildren_Should_TriggerRotations_AndRecoloring()
        {
            RedBlackTree <int> tree = new RedBlackTree <int>();

            for (int i = 0; i < 10; i++)
            {
                tree.Insert(i);
            }
            tree.Delete(tree.GetNode(8).Key);
            List <RedBlackTreeNode <int> > nodeList = tree.WalkInOrder();

            Assert.True(nodeList[5].Key == 5 && nodeList[5].Color == Red);
            Assert.True(nodeList[7].Key == 7 && nodeList[7].Color == Black);
            Assert.True(nodeList[8].Key == 9 && nodeList[8].Color == Black);

            //Assert.True(tree.Root.Right.Right.Key == 9);
            //Assert.True(tree.Root.Right.Right.Color == Black);
            var exception = Assert.Throws <KeyNotFoundException>(() => tree.GetNode(8));

            Assert.True(exception.Message == "Key not found.");
        }
        public void TestRemoveBalanced3()
        {
            var testTree = new RedBlackTree <int>();

            testTree.Insert(10);
            testTree.Insert(5);
            testTree.Insert(15);
            testTree.Insert(2);
            testTree.Insert(7);
            testTree.Insert(12);
            testTree.Insert(17);
            testTree.Insert(11);
            testTree.Insert(13);

            testTree.Remove(17);

            var actual   = testTree.PreOrder();
            var expected = new int[] { 10, 5, 2, 7, 12, 11, 15, 13 };

            Assert.AreEqual(expected, actual);
        }
        public void Insert_MultipleElements_ShouldBeInsertedCorrectly()
        {
            RedBlackTree <int> rbt = new RedBlackTree <int>();

            rbt.Insert(5);
            rbt.Insert(12);
            rbt.Insert(18);
            rbt.Insert(37);
            rbt.Insert(48);
            rbt.Insert(60);
            rbt.Insert(80);

            List <int> nodes = new List <int>();

            rbt.EachInOrder(nodes.Add);

            // Assert
            int[] expectedNodes = new int[] { 5, 12, 18, 37, 48, 60, 80 };

            CollectionAssert.AreEqual(expectedNodes, nodes);
        }
        public void TestRemoveBalanced2()
        {
            var testTree = new RedBlackTree <int>();

            testTree.Insert(1);
            testTree.Insert(9);
            testTree.Insert(8);

            var actual1   = testTree.PreOrder();
            var expected1 = new int[] { 8, 1, 9 };

            Assert.AreEqual(expected1, actual1);

            testTree.Insert(2);
            testTree.Remove(9);

            var actual2   = testTree.PreOrder();
            var expected2 = new int[] { 2, 1, 8 };

            Assert.AreEqual(expected2, actual2);
        }
示例#39
0
        public void AddKeyValuePairExample()
        {
            // Create a simple tree
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            // There should be 3 items in the tree.
            Assert.AreEqual(3, tree.Count);

            // The tree should contain all three keys
            Assert.IsTrue(tree.ContainsKey("cat"));
            Assert.IsTrue(tree.ContainsKey("dog"));
            Assert.IsTrue(tree.ContainsKey("canary"));

            // The value of the item with key "dog" must be 2.
            Assert.AreEqual(2, tree["dog"]);
        }
示例#40
0
        public void KeysExample()
        {
            // Build a simple tree.
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            // Retrieve the keys from the tree.
            var keys = tree.Keys;

            // The keys collection contains three items :
            // "cat", "dog", and "canary".
            Assert.AreEqual(3, keys.Count);

            Assert.IsTrue(keys.Contains("cat"));
            Assert.IsTrue(keys.Contains("dog"));
            Assert.IsTrue(keys.Contains("canary"));
        }
        private static void TestPrev(RedBlackTree <int, int> tree)
        {
            var node = tree.GetMaxNode();

            Assert.IsFalse(tree.Terminal(node));
            var count = 1;

            while (true)
            {
                var prev = tree.Prev(node);
                if (tree.Terminal(prev))
                {
                    break;
                }
                ++count;
                Assert.IsFalse(tree.Terminal(prev));
                Assert.IsTrue(node.Key > prev.Key);
                node = prev;
            }
            Assert.AreEqual(tree.Count, count);
        }
示例#42
0
        /// <summary>
        /// A private helper method that returns an enumerable that
        /// enumerates all the keys in a range.
        /// </summary>
        /// <param name="rangeTester">Defines the range to enumerate.</param>
        /// <param name="reversed">Should the keys be enumerated in reverse order?</param>
        /// <returns>An IEnumerable&lt;TKey&gt; that enumerates the keys in the given range.
        /// in the dictionary.</returns>
        private IEnumerator <TKey> EnumerateKeys(RedBlackTree <KeyValuePair <TKey, TValue> > .RangeTester rangeTester, bool reversed)
        {
            var isFirst = true;
            var lastKey = default(TKey);

            var pairs = reversed
                            ? _tree.EnumerateRangeReversed(rangeTester)
                            : _tree.EnumerateRange(rangeTester);

            // Enumerate pairs; yield a new key when the key changes.
            foreach (var pair in pairs)
            {
                if (isFirst || _keyComparer.Compare(lastKey, pair.Key) != 0)
                {
                    lastKey = pair.Key;
                    yield return(lastKey);
                }

                isFirst = false;
            }
        }
示例#43
0
        public void TestMethod1()
        {
            RedBlackTree <int> tree = new RedBlackTree <int>();

            tree.Insert(1);
            tree.Insert(2);
            tree.Insert(3);
            tree.Insert(4);
            tree.Insert(5);
            tree.Insert(6);
            tree.Insert(0);
            tree.Insert(-1);
            tree.Insert(11);
            tree.Insert(12);
            tree.Insert(21);
            tree.Insert(23);
            tree.Insert(10);
            tree.Insert(15);
            tree.Insert(16);
            tree.Insert(25);
        }
示例#44
0
        public void GetEnumeratorExample()
        {
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            var enumerator = tree.GetEnumerator();

            // Enumerate through the items in the tree, and write the contents
            // to the standard output.
            while (enumerator.MoveNext())
            {
                System.Console.Write("Key : ");
                System.Console.WriteLine(enumerator.Current.Key);
                System.Console.Write("Value : ");
                System.Console.WriteLine(enumerator.Current.Value);
            }
        }
示例#45
0
        public IActionResult RotateLeft(RotateNodeViewModel rotateNodeViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index"));
            }

            RedBlackTree tree = null;

            tree = treeToJsonConverter.JsonToTree(rotateNodeViewModel.SigmaGraphJson);
            var id    = Int32.Parse(rotateNodeViewModel.NodeId);
            var nodeD = tree.FindNode(id);

            tree.RotateLeft(nodeD);

            if (nodeD == null)
            {
                return(StatusCode(500, "Failed to rotate the node"));
            }
            return(Content(treeToJsonConverter.ToSigmaJson(tree)));
        }
示例#46
0
        public void Simple()
        {
            var redBlackTree = new RedBlackTree<int, string>();

            string value;

            for (var i = 0; i < 100; i++)
            {
                redBlackTree.Add(i, i.ToString());

                Assert.AreEqual(redBlackTree.Count, i + 1);
                Assert.IsTrue(redBlackTree.TryGetValue(i, out value));
                Assert.AreEqual(value, i.ToString());
            }

            Assert.IsFalse(redBlackTree.TryGetValue(101, out value));
            Assert.IsNull(value);

            Assert.IsFalse(redBlackTree.TryGetValue(102, out value));
            Assert.IsNull(value);
        }
示例#47
0
        public void AddKeyValuePairExample()
        {
            // Create a simple tree
            var tree = new RedBlackTree<string, int>
                                                 {
                                                     new KeyValuePair<string, int>("cat", 1),
                                                     new KeyValuePair<string, int>("dog", 2),
                                                     new KeyValuePair<string, int>("canary", 3)
                                                 };

            // There should be 3 items in the tree.
            Assert.AreEqual(3, tree.Count);

            // The tree should contain all three keys
            Assert.IsTrue(tree.ContainsKey("cat"));
            Assert.IsTrue(tree.ContainsKey("dog"));
            Assert.IsTrue(tree.ContainsKey("canary"));

            // The value of the item with key "dog" must be 2.
            Assert.AreEqual(2, tree["dog"]);
        }
示例#48
0
        public void GetEqualOrLessTest5()
        {
            RedBlackTree tree = new RedBlackTree();

            tree.RB_Insert(new TestObjectForEqualOrMore("zhu0", 0));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu0", 0));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu0", 0));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));

            RBNodeBase node = tree.GetEqualOrLess(new TestObjectForEqualOrMore("zhu1", 1));

            ValuesTest(node, "zhu0", 0);
            node = tree.GetNext(node);

            ValuesTest(node, "zhu2", 2);
            node = tree.GetNext(node);

            ValuesTest(node, "zhu2", 2);
        }
        public void RedBlackTree_Smoke_Test()
        {
            //insert test
            var tree = new RedBlackTree <int>();

            Assert.AreEqual(-1, tree.Root.GetHeight());

            tree.Insert(1);
            tree.Insert(2);
            tree.Insert(3);
            tree.Insert(4);
            tree.Insert(5);
            tree.Insert(6);
            tree.Insert(7);
            tree.Insert(8);
            tree.Insert(9);
            tree.Insert(10);
            tree.Insert(11);

            Assert.AreEqual(11, tree.Count);

            //IEnumerable test using linq
            Assert.AreEqual(tree.Count, tree.Count());
            Assert.AreEqual(tree.Count, tree.AsEnumerableDesc().Count());

            //delete
            tree.Delete(1);
            tree.Delete(2);
            tree.Delete(3);
            tree.Delete(4);
            tree.Delete(5);
            tree.Delete(6);
            tree.Delete(7);
            tree.Delete(8);
            tree.Delete(9);
            tree.Delete(10);
            tree.Delete(11);

            Assert.AreEqual(0, tree.Count);
        }
示例#50
0
        static void Main(string[] args)
        {
            var binaryTree   = new BinaryTree <int, int>();
            var avlTree      = new AVLTree <int, int>();
            var redBlackTree = new RedBlackTree <int, int>();
            var bTree        = new BTree <int, int>(2000);

            _timer = new Stopwatch();

            GenerateArray(_arrayLength);

            Console.WriteLine("Добавление:\n");

            var binaryTime   = GetAdditionTimeResult(binaryTree);
            var avlTime      = GetAdditionTimeResult(avlTree);
            var redBlackTime = GetAdditionTimeResult(redBlackTree);

            //var bTime = GetAdditionTimeResult(bTree);

            Console.WriteLine("\nПоиск:\n");

            binaryTime   += GetSearchingTimeResult(binaryTree);
            avlTime      += GetSearchingTimeResult(avlTree);
            redBlackTime += GetSearchingTimeResult(redBlackTree);
            //bTime += GetSearchingTimeResult(bTree);

            Console.WriteLine("\nУдаление:\n");

            binaryTime   += GetRemovingTimeResult(binaryTree);
            avlTime      += GetRemovingTimeResult(avlTree);
            redBlackTime += GetRemovingTimeResult(redBlackTree);
            //bTime += GetRemovingTimeResult(bTree);

            Console.WriteLine("\nОбщее время:\n");

            GetTotalTime(binaryTree, binaryTime);
            GetTotalTime(avlTree, avlTime);
            GetTotalTime(redBlackTree, redBlackTime);
            //GetTotalTime(bTree, bTime);
        }
示例#51
0
        public void ClearExample()
        {
            // Create a simple tree
            var tree = new RedBlackTree <string, int>
            {
                new KeyValuePair <string, int>("cat", 1),
                new KeyValuePair <string, int>("dog", 2),
                new KeyValuePair <string, int>("canary", 3)
            };

            // There should be 3 items in the tree.
            Assert.AreEqual(3, tree.Count);

            // Clear the tree
            tree.Clear();

            // The tree should be empty.
            Assert.AreEqual(0, tree.Count);

            // No cat here..
            Assert.IsFalse(tree.ContainsKey("cat"));
        }
示例#52
0
	public void RBDelete3Test()
	{
		RedBlackTree<int, string> rb = new RedBlackTree<int,string>();
		
		for (int i = 99; i >= 0; i--) {
			rb.Insert(i, i.ToString());
		}
		
		for (int i = 0; i < 50; i++) {
			rb.Delete(49 - i);
			
			RBAssertPresent(rb, 0, 49 - i - 1);
			RBAssertPresent(rb, 50 + i, 99);
			RBAssertNotPresent(rb, 49 - i, 50 + i - 1);
			
			rb.Delete(50 + i);
			
			RBAssertPresent(rb, 0, 49 - i - 1);
			RBAssertPresent(rb, 50 + i + 1, 99);
			RBAssertNotPresent(rb, 49 - i, 50 + i );
		}
	}
示例#53
0
        public void GetEqualOrLessTest6()
        {
            RedBlackTree tree = new RedBlackTree();

            tree.RB_Insert(new TestObjectForEqualOrMore("zhu1", 1));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu1", 1));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu1", 1));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));
            tree.RB_Insert(new TestObjectForEqualOrMore("zhu2", 2));

            tree.GetEqualOrLess(new TestObjectForEqualOrMore("zhu0", 0));
            //ValuesTest( node, "zhu1", 1 );
            //node = tree.GetNext( node );

/*
 *          ValuesTest( node, "zhu2", 2 );
 *          node = tree.GetNext( node );
 *
 *          ValuesTest( node, "zhu2", 2 );
 */
        }
示例#54
0
        public void TestUsage1()
        {
            RedBlackTree<Guid, string> tree = new RedBlackTree<Guid, string>();
            Guid item1 = Guid.NewGuid();
            Guid item2 = Guid.NewGuid();
            for (int i = 0; i < 100; i++)
            {
                tree.Add(Guid.NewGuid(), DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));
            }
            tree.Add(item1, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));
            tree.Add(item2, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

            Assert.AreEqual(102, tree.Count, "Should be 102 items in the tree");
            Assert.IsTrue(tree.ContainsKey(item1), "Should contain item 1");
            Assert.IsTrue(tree.ContainsKey(item2), "Should contain item 2");
            tree.Remove(item1);
            Assert.AreEqual(101, tree.Count, "Should be 101 items in the tree");
            Assert.IsFalse(tree.ContainsKey(item1), "Should not contain item 1");
            tree.Remove(item2);
            Assert.AreEqual(100, tree.Count, "Should be 100 items in the tree");
            Assert.IsFalse(tree.ContainsKey(item2), "Should not contain item 2");
        }
        private static void TestTryPrev(RedBlackTree <int, int> tree)
        {
            if (!tree.TryGetMaxNode(out var node))
            {
                Assert.Fail();
            }
            Assert.IsFalse(tree.Terminal(node));
            var count = 1;

            while (true)
            {
                if (!tree.TryPrev(node, out var prev))
                {
                    break;
                }
                ++count;
                Assert.IsFalse(tree.Terminal(prev));
                Assert.IsTrue(node.Key > prev.Key);
                node = prev;
            }
            Assert.AreEqual(tree.Count, count);
        }
示例#56
0
	public void RBDelete2Test()
	{
		RedBlackTree<int, string> rb = new RedBlackTree<int,string>();
		
		for (int i = 19; i >= 0; i--) {
			rb.Insert(i, i.ToString());
		}
				
		for (int i = 0; i < 10; i++) {
			rb.Delete(9 - i);
			
			RBAssertPresent(rb, 0, 9 - i - 1);
			RBAssertPresent(rb, 10 + i, 19);
			RBAssertNotPresent(rb, 9 - i, 10 + i - 1);
			
			rb.Delete(10 + i);
			
			RBAssertPresent(rb, 0, 9 - i - 1);
			RBAssertPresent(rb, 10 + i + 1, 19);
			RBAssertNotPresent(rb, 9 - i, 10 + i );
		}
	}
        private static void TestTryNext(RedBlackTree <int, int> tree)
        {
            if (!tree.TryGetMinNode(out var node))
            {
                Assert.Fail();
            }
            Assert.IsFalse(tree.Terminal(node));
            var count = 1;

            while (true)
            {
                if (!tree.TryNext(node, out var next))
                {
                    break;
                }
                ++count;
                Assert.IsFalse(tree.Terminal(next));
                Assert.IsTrue(node.Key < next.Key);
                node = next;
            }
            Assert.AreEqual(tree.Count, count);
        }
		void UpdateNode (RedBlackTree<TreeNode>.RedBlackTreeNode node)
		{
			if (node == null)
				return;
			
			int count       = 1;
			int totalLength = node.value.Length;
			
			if (node.left != null) {
				count       += node.left.value.count;
				totalLength += node.left.value.totalLength;
			}
			
			if (node.right != null) {
				count       += node.right.value.count;
				totalLength += node.right.value.totalLength;
			}
			if (count != node.value.count || totalLength != node.value.totalLength) {
				node.value.count       = count;
				node.value.totalLength = totalLength;
				UpdateNode (node.parent);
			}
		}
示例#59
0
文件: Visit.cs 项目: havok/ngenerics
        public void Simple()
        {
            var tree = new RedBlackTree<int, string>();

            for (var i = 0; i < 50; i++)
            {
                tree.Add(i, i.ToString());
            }

            var visitor = new KeyTrackingVisitor<int, string>();
            tree.AcceptVisitor(visitor);

            Assert.IsFalse(visitor.HasCompleted);

            Assert.AreEqual(visitor.TrackingList.Count, 50);

            var list = new List<int>(visitor.TrackingList);

            for (var i = 0; i < 50; i++)
            {
                Assert.IsTrue(list.Contains(i));
            }
        }
示例#60
0
        public void Simple()
        {
            var redBlackTree = GetTestTree(20);
            var keys = redBlackTree.Keys;

            Assert.AreEqual(keys.Count, 20);

            var counter = 0;

            using (var enumerator = keys.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Assert.AreEqual(enumerator.Current, counter);
                    counter++;
                }
            }

            redBlackTree = new RedBlackTree<int, string>();
            keys = redBlackTree.Keys;

            Assert.IsNotNull(keys);
            Assert.AreEqual(keys.Count, 0);
        }