Пример #1
0
        public void CheckHeight()
        {
            RedBlackTree <int, int> Tree = new RedBlackTree <int, int>();

            Assert.AreEqual(Tree.GetHeight(), -1);

            Tree.Add(new Node <int, int>(0, 0));
            Assert.AreEqual(Tree.GetHeight(), 0);

            Tree.Add(new Node <int, int>(1, 1));
            Assert.AreEqual(Tree.GetHeight(), 1);

            Tree.Add(new Node <int, int>(2, 2));
            Tree.Add(new Node <int, int>(3, 3));
            Tree.Add(new Node <int, int>(4, 4));
            Assert.AreEqual(Tree.GetHeight(), 2);

            Tree.Delete(new Node <int, int>(0, 0));
            Tree.Delete(new Node <int, int>(1, 1));
            Tree.Delete(new Node <int, int>(2, 2));
            Assert.AreEqual(Tree.GetHeight(), 1);

            Tree.Delete(new Node <int, int>(3, 3));
            Assert.AreEqual(Tree.GetHeight(), 0);

            Tree.Delete(new Node <int, int>(4, 4));
            Assert.AreEqual(Tree.GetHeight(), -1);
        }
Пример #2
0
        public void CountExample()
        {
            var tree = new RedBlackTree <string, int>();

            // Tree count is 0.
            Assert.AreEqual(0, tree.Count);

            // Add a cat.
            tree.Add(new KeyValuePair <string, int>("cat", 1));

            // Tree count is 1.
            Assert.AreEqual(1, tree.Count);

            // Add a dog
            tree.Add(new KeyValuePair <string, int>("dog", 2));

            // Tree count is 2.
            Assert.AreEqual(2, tree.Count);

            // Clear the tree - thereby removing all items contained.
            tree.Clear();

            // Tree is empty again with 0 count.
            Assert.AreEqual(0, tree.Count);
        }
Пример #3
0
        public void InsertDuplicate()
        {
            RedBlackTree <int, int> Tree = new RedBlackTree <int, int>();

            Tree.Add(new Node <int, int>(0, 0));
            Tree.Add(new Node <int, int>(0, 0));
        }
Пример #4
0
        private RedBlackTree <Byte, Char> CreateFullRBT()
        {
            // A, B, C, D, E, F, G, H, I, K
            // 1, 2, 3, 4, 5, 6, 7, 8, 9, 11
            RedBlackTree <Byte, Char> bst = new RedBlackTree <Byte, Char>();

            //         6F
            //       /   \
            //     4D     7G
            //     / \     \
            //   2B  5E    11K
            //   / \       /
            // 1A  3C     9I
            //           /
            //         8H

            bst.Add(6, 'F');
            bst.Add(4, 'D');
            bst.Add(7, 'G');
            bst.Add(2, 'B');
            bst.Add(11, 'K');
            bst.Add(9, 'I');
            bst.Add(5, 'E');
            bst.Add(8, 'H');
            bst.Add(3, 'C');
            bst.Add(1, 'A');

            return(bst);
        }
Пример #5
0
        public void VerifyTwoLeftsRBTree()
        {
            RedBlackTree <long, string> testTree = new RedBlackTree <long, string>();

            testTree.Add(5, "Test Starts Root");
            testTree.Add(3, "Test Becomes Root");
            testTree.Add(1, "Test 1");

            BinaryTree <long, string> .BinaryTreeNode currentNode = testTree.Root;

            Assert.NotNull(currentNode);
            Assert.Equal(3, currentNode.Key);
            Assert.Equal("Test Becomes Root", currentNode.Value);

            Assert.NotNull(currentNode.Right);
            Assert.NotNull(currentNode.Left);

            currentNode = testTree.Root.Right;

            Assert.Equal(5, currentNode.Key);
            Assert.Equal("Test Starts Root", currentNode.Value);

            Assert.Null(currentNode.Right);
            Assert.Null(currentNode.Left);

            currentNode = currentNode.Sibling();

            Assert.Null(currentNode.Right);
            Assert.Null(currentNode.Left);

            Assert.Equal(1, currentNode.Key);
            Assert.Equal("Test 1", currentNode.Value);
        }
Пример #6
0
        public void AddCaseLeftRightRoot()
        {
            RedBlackTree <int, int> tree = new RedBlackTree <int, int>();

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

            //        B3
            //    R1
            //      R2
            //
            // left-left case, root rotate
            //
            //    B2
            // R1    R3
            //

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

            AssertOrder(e1, e2, e3);

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

            AssertLeaves(e1, e3);

            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(e1.Red);
            Assert.IsTrue(e3.Red);
        }
Пример #7
0
        public void TestAdd()
        {
            RedBlackTree <int, string> tree = new RedBlackTree <int, string>();

            for (int i = 0; i < 100; i++)
            {
                tree.Add(i, i.ToString());

                Assert.AreEqual(tree.ContainsKey(i), true);
                Assert.AreEqual(tree.Count, i + 1);
            }

            for (int i = 300; i > 200; i--)
            {
                tree.Add(i, i.ToString());

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

            for (int i = 100; i < 200; i++)
            {
                tree.Add(i, i.ToString());

                Assert.AreEqual(tree.ContainsKey(i), true);
                Assert.AreEqual(tree.Count, 100 + i + 1);
            }
        }
        public void ProvideOrder_AfterAdding()
        {
            foreach (var x in new[] { 5, 4, 3, 2, 1 })
            {
                tree.Add(x);
            }

            Assert.That(tree.ToList(), Is.EquivalentTo(new[] { 1, 2, 3, 4, 5 }));
        }
Пример #9
0
        /// <summary>
        ///A test for Clear
        ///</summary>
        public void ClearTestHelper <T>()
        {
            RedBlackTree <double> target = new RedBlackTree <double>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Clear();
            Assert.IsNull(target.Root);
        }
Пример #10
0
        public void RBleft()
        {
            RedBlackTree <int> rbtre = new RedBlackTree <int>();

            rbtre.Add(8);
            rbtre.Add(4);
            rbtre.Add(10);

            Assert.AreEqual(4, rbtre.Root.Left.Value);
        }
Пример #11
0
        public void Test_Contains()
        {
            var bst = new RedBlackTree <Byte, Char>();

            bst.Add(1, 'A');
            bst.Add(2, 'B');

            Assert.True(bst.Contains(1));
            Assert.True(bst.Contains(2));
        }
Пример #12
0
        public void RBright()
        {
            RedBlackTree <int> rbtre = new RedBlackTree <int>();

            rbtre.Add(8);
            rbtre.Add(4);
            rbtre.Add(10);


            Assert.AreEqual(10, rbtre.Root.Right.Value);
        }
Пример #13
0
        public void AddTest()
        {
            const int a = 5;
            const int b = 3;

            var tree = new RedBlackTree <int>();

            tree.Add(a);
            tree.Add(b);

            Assert.IsTrue(tree.Exists(a) && tree.Exists(b), "Added node with wrong key");
        }
Пример #14
0
        public void TestAddBug()
        {
            var      tree = new RedBlackTree <TestNode> ();
            TestNode t1   = new TestNode(1);
            TestNode t2   = new TestNode(2);
            TestNode t3   = new TestNode(3);

            tree.Add(t1);
            tree.Add(t2);
            tree.Add(t3);
            Assert.AreEqual(3, tree.Count);
        }
Пример #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 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);
        }
Пример #17
0
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion


        /// <summary>
        ///A test for Add
        ///</summary>
        public void AddTestHelper <T>()
        {
            RedBlackTree <double> target = new RedBlackTree <double>();
            double data = 3;

            target.Add(1);
            target.Add(2);
            target.Add(data);
            SearchResult actual = target.Contains(data);

            Assert.IsNotNull(actual.SearchPath);
        }
        public RedBlackTreeView()
        {
            InitializeComponent();
            RedBlackTree <int> RBtree = new RedBlackTree <int>();

            RBtree.Add(5);
            RBtree.Add(4);
            RBtree.Add(3);
            RBtree.Add(7);
            var tree = new RedBlackTreeViewModel <int>(RBtree);

            this.DataContext = tree;
        }
Пример #19
0
        public void RemoveTest()
        {
            const int a = 5;
            const int b = 3;

            var tree = new RedBlackTree <int>();

            tree.Add(a);
            tree.Add(b);
            tree.Remove(b);

            Assert.IsTrue(tree.Exists(a) && !tree.Exists(b), "Deleted node with wrong key");
        }
Пример #20
0
        public void Remove_SimpleCases_TreeStillValid()
        {
            var tree = new RedBlackTree <int>();

            tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 });
            tree.Remove(6);
            tree.Count.Should().Be(9);
            tree.Contains(6).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 1, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 11, 17, 15, 25, 22, 27 }).Should().BeTrue();

            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 });
            tree.Remove(1);
            tree.Count.Should().Be(9);
            tree.Contains(1).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 6, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 6, 11, 17, 15, 25, 22, 27 }).Should().BeTrue();

            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 });
            tree.Remove(17);
            tree.Count.Should().Be(9);
            tree.Contains(17).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 22, 25, 27 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 22, 15, 25, 27 }).Should().BeTrue();

            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 });
            tree.Remove(25);
            tree.Count.Should().Be(9);
            tree.Contains(25).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 17, 22, 27 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 17, 15, 27, 22 }).Should().BeTrue();

            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 7, 3, 18, 10, 22, 8, 11, 26 });
            tree.Remove(18);
            tree.Count.Should().Be(7);
            tree.Contains(18).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 3, 7, 8, 10, 11, 22, 26 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 7, 3, 22, 10, 8, 11, 26 }).Should().BeTrue();

            tree = new RedBlackTree <int>();
            tree.Add(1);
            tree.Add(2);
            tree.Remove(1);
            tree.Count.Should().Be(1);
            tree.GetKeysInOrder().SequenceEqual(new[] { 2 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 2 }).Should().BeTrue();
        }
Пример #21
0
        public void VerifyRBTreeLeftBalance()
        {
            RedBlackTree <long, string> testTree = new RedBlackTree <long, string>();

            testTree.Add(9, "9");
            testTree.Add(8, "8");
            testTree.Add(7, "7");
            testTree.Add(6, "6");
            testTree.Add(5, "5");
            testTree.Add(4, "4");
            testTree.Add(3, "3");
            testTree.Add(2, "2");
            testTree.Add(1, "1");

            RedBlackTree <long, string> .RedBlackTreeNode currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)testTree.Root;


            Assert.Equal(6, currentNode.Key);
            Assert.Equal(0, currentNode.Color);

            currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Left;

            Assert.Equal(4, currentNode.Key);
            Assert.Equal(1, currentNode.Color);

            RedBlackTree <long, string> .RedBlackTreeNode siblingNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Sibling();

            Assert.Equal(8, siblingNode.Key);
            Assert.Equal(1, siblingNode.Color);

            currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Left;
            Assert.Equal(2, currentNode.Key);
            Assert.Equal(0, currentNode.Color);

            siblingNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Sibling();
            Assert.Equal(5, siblingNode.Key);
            Assert.Equal(0, siblingNode.Color);

            currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Left;
            Assert.Equal(1, currentNode.Key);
            Assert.Equal(1, currentNode.Color);

            siblingNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Sibling();
            Assert.Equal(3, siblingNode.Key);
            Assert.Equal(1, currentNode.Color);

            currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)testTree.Root.Right.Left;
            Assert.Equal(7, currentNode.Key);
            Assert.Equal(0, currentNode.Color);

            currentNode = (RedBlackTree <long, string> .RedBlackTreeNode)currentNode.Sibling();
            Assert.Equal(9, currentNode.Key);
            Assert.Equal(0, currentNode.Color);
        }
Пример #22
0
        public void Add_KeyAlreadyInTree_ThrowsException()
        {
            var tree = new RedBlackTree <int>();

            tree.AddRange(new[] { 1, 2, 3, 4, 5 });
            Assert.Throws <ArgumentException>(() => tree.Add(1));
        }
Пример #23
0
        public void Set_Test()
        {
            // Arrange
            RedBlackTree <int> redBlackTree = new RedBlackTree <int>();
            BPTree <int, int>  bPlusTree    = new BPTree <int, int>();

            // Act
            for (int i = 0; i < 100; i++)
            {
                redBlackTree.Add(i);
            }
            for (int i = 50; i < 150; i++)
            {
                bPlusTree.Add(i, i);
            }
            Set <int> bpTreeSet = new Set <int>(bPlusTree);
            Set <int> rbTreeSet = new Set <int>(redBlackTree);
            Set <int> checkSet  = new Set <int>();

            for (int i = 0; i < 50; i++)
            {
                checkSet.Add(i);
                checkSet.Add(i + 100);
            }
            // Assert
            Assert.IsTrue(bpTreeSet.SymmetricExceptWith(rbTreeSet).set.SetEquals(checkSet.set));
        }
        public void PreviousShouldBeAbleToWalkTheTreeBackward()
        {
            int seed = 12345;

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

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

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

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

                tree.Add(key, i);

                if (IsFibonacci(i))
                {
                    List <RedBlackTreeNode <int, int> > actualNodes = new List <RedBlackTreeNode <int, int> >();
                    for (RedBlackTreeNode <int, int> node = tree.MaximumNode; node != null; node = node.Previous())
                    {
                        actualNodes.Add(node);
                    }
                    int[] actualKeys   = actualNodes.Select(n => n.Key).ToArray();
                    int[] expectedKeys = keys.OrderByDescending(k => k).ToArray();

                    CollectionAssert.AreEqual(actualKeys, expectedKeys);
                }
            }
        }
        public void TreeShouldBeValidAfterManyRandomDeletions()
        {
            int seed = 12345;

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

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

            List <Tuple <int, int> > insertions = new List <Tuple <int, int> >();

            for (int i = 0; i < 500; i++)
            {
                int key = RandomNext();
                insertions.Add(new Tuple <int, int>(key, i));

                Assert.That(tree.Count, Is.EqualTo(i));
                Assert.That(tree.TryGetValue(key, out int oldValue), Is.False);
                Assert.That(tree.ContainsKey(key), Is.False);

                tree.Add(key, i);

                if (IsFibonacci(i))
                {
                    tree.Validate();
                }

                Assert.That(tree.ContainsKey(key), Is.True);
                Assert.That(tree[key], Is.EqualTo(i));
                Assert.That(tree.TryGetValue(key, out int newValue), Is.True);
                Assert.That(newValue, Is.EqualTo(i));
                Assert.That(tree.Count, Is.EqualTo(i + 1));
            }

            for (int i = 0; i < 500; i++)
            {
                int key   = insertions[i].Item1;
                int value = insertions[i].Item2;

                Assert.That(tree.ContainsKey(key), Is.True);
                Assert.That(tree[key], Is.EqualTo(value));
                Assert.That(tree.TryGetValue(key, out int newValue), Is.True);
                Assert.That(newValue, Is.EqualTo(value));
                Assert.That(tree.Count, Is.EqualTo(500 - i));

                Assert.That(tree.Remove(key), Is.True);

                if (IsFibonacci(i))
                {
                    tree.Validate();
                }

                Assert.That(tree.ContainsKey(key), Is.False);
                Assert.That(tree.TryGetValue(key, out int oldValue), Is.False);
                Assert.That(tree.Count, Is.EqualTo(500 - i - 1));
            }
        }
Пример #26
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            _ = inputStream.ReadInt();
            var d = inputStream.ReadIntArray();

            _ = inputStream.ReadInt();
            var needed = inputStream.ReadIntArray();

            var set = new RedBlackTree <int>();

            foreach (var di in d)
            {
                set.Add(di);
            }

            foreach (var p in needed)
            {
                if (!set.Remove(p))
                {
                    yield return("NO");

                    yield break;
                }
            }

            yield return("YES");
        }
Пример #27
0
        public void Add_Case3_FormsCorrectTree()
        {
            var tree = new RedBlackTree <int>();

            tree.Add(5);
            tree.Count.Should().Be(1);
        }
Пример #28
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());
        }
Пример #29
0
        public void RedBlackTree_AddingSearchingDeleting()
        {
            // Arrange
            var redBlackTree = new RedBlackTree <int>();

            // Act
            for (int i = 0; i < 1000; i++)
            {
                redBlackTree.Add(i);
            }
            redBlackTree.Remove(17);
            redBlackTree.Remove(93);
            // Assert
            for (int i = 0; i < 1000; i++)
            {
                if (i != 17 && i != 93)
                {
                    Assert.AreEqual(redBlackTree.Search(i).Data, i);
                }
                else
                {
                    Assert.AreEqual(redBlackTree.Search(i), null);
                }
            }
        }
Пример #30
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;
        }
Пример #31
0
        private static int BuildStorageEntry(DirectoryEntry storageEntry)
        {
            RedBlackTree <DirectoryEntry> redBlackTree = new RedBlackTree <DirectoryEntry>();

            foreach (DirectoryEntry directoryEntry in storageEntry.Members.Values)
            {
                redBlackTree.Add(directoryEntry);
            }
            foreach (RedBlackTreeNode <DirectoryEntry> current in redBlackTree.InorderTreeWalk(redBlackTree.Root))
            {
                DirectoryEntry directoryEntry = current.Data;
                directoryEntry.NodeColor     = DirectoryTree.GetNodeColor(current.Color);
                directoryEntry.LeftChildDID  = DirectoryTree.GetNodeID(current.Left);
                directoryEntry.RightChildDID = DirectoryTree.GetNodeID(current.Right);
                if (directoryEntry.Members.Count > 0)
                {
                    directoryEntry.EntryType          = 1;
                    directoryEntry.MembersTreeNodeDID = DirectoryTree.BuildStorageEntry(directoryEntry);
                }
                else
                {
                    directoryEntry.EntryType          = 2;
                    directoryEntry.MembersTreeNodeDID = -1;
                }
            }
            return(redBlackTree.Root.Data.ID);
        }
Пример #32
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);
        }
Пример #33
0
        public void Container_RedBlackTree()
        {
            // Arrange
            RedBlackTree <int> redBlackTree = new RedBlackTree <int>();
            Collection <int>   keys         = new Collection <int>();

            // Act
            for (int i = 0; i < 100; i++)
            {
                redBlackTree.Add(i);
                keys.Add(100 + i);
            }
            Container <int, int> container = new Container <int, int>(redBlackTree, keys);

            container.RemoveByKey(120);
            container.RemoveByKey(180);
            // Assert
            for (int i = 100; i < 200; i++)
            {
                if (i != 120 && i != 180)
                {
                    Assert.AreEqual(container.GetValue(i), i - 100);
                }
                else
                {
                    Assert.AreEqual(container.GetValue(i), default);
                }
            }
        }
        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));
        }
Пример #35
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;
        }
Пример #36
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);
        }
Пример #37
0
        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")));
        }
Пример #38
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");
        }
Пример #39
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));
        }
Пример #41
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();
        }
Пример #42
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);
            }
        }
Пример #43
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);
        }
Пример #44
0
        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));
            }
        }
        public void AddCaseRoot()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            

            tree.Add(1, 1);

            //   B1
            //

            var e1 = tree.RootElement;

            AssertRoot(e1);
            Assert.IsTrue(!e1.Red);
        }
        public void AddCaseBlackParent()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(1, 1);


            tree.Add(2, 2);

            //    B1
            //       R2  
            //

            var e1 = tree.RootElement;
            var e2 = e1.Right;

            AssertOrder(e1, e2);

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

            Assert.IsTrue(!e1.Red);
            Assert.IsTrue(e2.Red);
        }
Пример #47
0
        public void StressTestRandomData()
        {
            var data = new List<int>();
            var redBlackTree = new RedBlackTree<int, string>();

            var rand = new Random(Convert.ToInt32(DateTime.Now.Ticks % Int32.MaxValue));

            for (var i = 0; i < 2000; i++)
            {
                var randomNumber = rand.Next(100000);

                while (data.Contains(randomNumber))
                {
                    randomNumber = rand.Next(100000);
                }

                data.Add(randomNumber);
                redBlackTree.Add(randomNumber, randomNumber.ToString());

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

                foreach (var t in data)
                {
                    Assert.IsTrue(redBlackTree.ContainsKey(t));
                }
            }

            while (data.Count != 0)
            {
                Assert.IsTrue(redBlackTree.Remove(data[0]));

                Assert.IsFalse(redBlackTree.ContainsKey(data[0]));

                data.RemoveAt(0);

                Assert.AreEqual(redBlackTree.Count, data.Count);

                foreach (var t in data)
                {
                    Assert.IsTrue(redBlackTree.ContainsKey(t));
                }
            }
        }
        public void AddCaseRightLeft()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(2, 2);
            tree.Add(3, 3);
            tree.Add(1, 1);
            tree.Add(5, 5);


            tree.Add(4, 4);

            //    B2
            // B1    B3
            //          R5
            //         R3
            //
            // right-right case
            //
            //    B2
            // B1    B4
            //     R3  R5

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

            AssertOrder(e1, e2, e3, e4, e5);

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

            AssertLeaves(e1, e3, e5);

            Assert.IsTrue(!e1.Red);
            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(e3.Red);
            Assert.IsTrue(!e4.Red);
            Assert.IsTrue(e5.Red);
        }
        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);
        }
        public void AddCaseParentAndUncleRedRoot2()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(3, 3);
            tree.Add(4, 4);
            tree.Add(2, 2);

            tree.Add(1, 1);

            //       B3
            //    R2    R4
            // R1
            // left-left case, root rotate
            //
            //       B3
            //    B2    B4
            // R1 

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

            AssertOrder(e1, e2, e3, e4);

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

            AssertLeaves(e1, e4);
            Assert.IsNull(e2.Right);

            Assert.IsTrue(e1.Red);
            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(!e3.Red);
            Assert.IsTrue(!e4.Red);
        }
        public void AddCaseLeftRightRoot()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(3, 3);
            tree.Add(1, 1);
            tree.Add(2, 2);

            //        B3
            //    R1  
            //      R2
            //
            // left-left case, root rotate
            //
            //    B2
            // R1    R3
            //

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

            AssertOrder(e1, e2, e3);

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

            AssertLeaves(e1, e3);

            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(e1.Red);
            Assert.IsTrue(e3.Red);
        }
        public void AddCaseParentAndUncleRed2()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(5, 5);
            tree.Add(2, 2);
            tree.Add(6, 6);
            tree.Add(1, 1);
            tree.Add(4, 4);

            tree.Add(3, 3);

            //            B5
            //       B2         B6
            //    R1   R4
            //        R3 
            // left-left case
            //            B5
            //       R2         B6
            //    B1   B4
            //        R3 


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

            AssertOrder(e1, e2, e3, e4, e5, e6);

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

            AssertLeaves(e1, e3, e6);
            Assert.IsNull(e4.Right);

            Assert.IsTrue(!e1.Red);
            Assert.IsTrue(e2.Red);
            Assert.IsTrue(e3.Red);
            Assert.IsTrue(!e4.Red);
            Assert.IsTrue(!e5.Red);
            Assert.IsTrue(!e6.Red);
        }
        public void AddCaseLeftRight()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
            tree.Add(4, 4);
            tree.Add(3, 3);
            tree.Add(5, 5);
            tree.Add(1, 1);

            tree.Add(2, 2);

            //            B4
            //        B3      B5
            //    R1
            //      R2 
            // left-left case
            //
            //          B4
            //      B2       B5
            //    R1  R3


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

            AssertOrder(e1, e2, e3, e4, e5);

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

            AssertLeaves(e1, e3, e5);

            Assert.IsTrue(e1.Red);
            Assert.IsTrue(!e2.Red);
            Assert.IsTrue(e3.Red);
            Assert.IsTrue(!e4.Red);
            Assert.IsTrue(!e5.Red);
        }
        public void StructureIntegrity()
        {
            RedBlackTree<int, int> tree = new RedBlackTree<int, int>();

            int range = 10;
            int[] order = new[] { 1, 3, 2, 5, 6 };

            var q = order
                .SelectMany(x => Enumerable.Range((x - 1) * range + 1, range));


            foreach (int i in q)
            {
                Assert.IsFalse(tree.ContainsKey(i));

                tree.Add(i, i);

                AssertStructure(tree.RootElement);
                Assert.IsTrue(tree.ContainsKey(i));
            }

            foreach (int i in q)
            {
                AssertStructure(tree.RootElement);
                Assert.IsTrue(tree.ContainsKey(i));

                tree.Remove(i);

                Assert.IsFalse(tree.ContainsKey(i));
            }

        }
Пример #55
0
        public void CountExample()
        {
            var tree = new RedBlackTree<string, int>();

            // Tree count is 0.
            Assert.AreEqual(0, tree.Count);

            // Add a cat.
            tree.Add(new KeyValuePair<string, int>("cat", 1));

            // Tree count is 1.
            Assert.AreEqual(1, tree.Count);

            // Add a dog
            tree.Add(new KeyValuePair<string, int>("dog", 2));

            // Tree count is 2.
            Assert.AreEqual(2, tree.Count);

            // Clear the tree - thereby removing all items contained.
            tree.Clear();

            // Tree is empty again with 0 count.
            Assert.AreEqual(0, tree.Count);
        }
Пример #56
0
        private static void duplicates(int n)
        {
            var rand = Accord.Math.Tools.Random;

            RedBlackTree<int> t = new RedBlackTree<int>();

            // Create a vector of random numbers with duplicates
            int[] k = new int[n];
            for (int i = 0; i < k.Length; i++) 
                k[i] = i;

            Vector.Shuffle(k);

            int[] sorted = (int[])k.Clone();
            Array.Sort(sorted);

            // Populate the tree with numbers
            for (int i = 0; i < k.Length; i++)
            {
                var node = t.Add(k[i]);

                Assert.IsNotNull(node);
                Assert.AreEqual(k[i], node.Value);

                Assert.IsTrue(t.check());
            }

            Assert.AreEqual(k.Length, t.Count);


            // Check that all elements are in the tree
            for (int i = 0; i < k.Length; i++)
            {
                var node = t.Find(k[i]);

                Assert.IsNotNull(node);
                Assert.AreEqual(k[i], node.Value);

                Assert.IsTrue(t.Contains(k[i]));
                Assert.IsTrue(t.Contains(node));
            }

            // Enumerate the values (must be in order)
            int arrayIndex = 0;
            foreach (var node in t)
                Assert.AreEqual(sorted[arrayIndex++], node.Value);



            // Populate the tree with the same numbers
            for (int i = 0; i < k.Length; i++)
            {
                var node = t.Add(k[i]);

                Assert.IsNotNull(node);
                Assert.AreEqual(k[i], node.Value);

                Assert.IsTrue(t.check());
            }

            Assert.IsTrue(t.check());

            // Enumerate the values (must be in order)
            arrayIndex = 0;
            foreach (var node in t)
                Assert.AreEqual(sorted[arrayIndex++], node.Value);
        }
Пример #57
0
        private static void run(int n)
        {
            var rand = Accord.Math.Tools.Random;

            RedBlackTree<int> t = new RedBlackTree<int>(allowDuplicates: true);

            // Create a vector of random numbers
            int[] k = new int[n];
            for (int i = 0; i < k.Length; i++)
                k[i] = rand.Next(k.Length);

            int[] sorted = (int[])k.Clone();
            Array.Sort(sorted);

            // Populate the tree with numbers
            for (int i = 0; i < k.Length; i++)
            {
                var node = t.Add(k[i]);

                Assert.IsNotNull(node);
                Assert.AreEqual(k[i], node.Value);

                Assert.IsTrue(t.check());
            }

            Assert.AreEqual(k.Length, t.Count);


            // Check that all elements are in the tree
            for (int i = 0; i < k.Length; ++i)
            {
                var node = t.Find(k[i]);

                Assert.IsNotNull(node);
                Assert.AreEqual(k[i], node.Value);

                Assert.IsTrue(t.Contains(k[i]));
                Assert.IsTrue(t.Contains(node));
            }

            // Enumerate the values (must be in order)
            int arrayIndex = 0;
            foreach (var node in t)
                Assert.AreEqual(sorted[arrayIndex++], node.Value);



            // Start from min and go navigating up to max
            var min = t.Min();
            Assert.IsNotNull(min);
            Assert.AreEqual(k.Min(), min.Value);

            for (int i = 0; i < k.Length; i++)
            {
                Assert.IsNotNull(min);
                min = t.GetNextNode(min);
            }
            Assert.IsNull(min); // the last should be null.

            // Start from max and go navigating down to min
            var max = t.Max();
            Assert.AreEqual(k.Max(), max.Value);
            for (int i = 0; i < k.Length; i++)
            {
                Assert.IsNotNull(max);
                max = t.GetPreviousNode(max);
            }
            Assert.IsNull(max); // the last should be null.


            // Exercise the tree
            for (int M = k.Length; M > 0; M--)
            {
                int knew = rand.Next(k.Length); // random new key 
                int j = rand.Next(M); // random original key to replace 
                int i;

                for (i = 0; i < k.Length; i++)
                    if (k[i] >= 0)
                        if (j-- == 0)
                            break;


                if (i >= k.Length)
                    Assert.Fail();

                int kd = k[i];

                var node = t.Find(kd);
                Assert.IsNotNull(node);

                node.Value = knew;

                Assert.IsNotNull(t.Resort(node));
                Assert.IsTrue(t.check());

                k[i] = -1 - knew;

                Assert.AreEqual(k.Length, t.Count);
            }

            for (int i = 0; i < k.Length; i++)
                k[i] = -1 - k[i]; // undo negation above




            // check the localization functions
            for (int i = 0; i < k.Length; i++)
            {
                int kd = (int)(0.01 * (rand.Next() % (k.Length * 150) - k.Length * 25));

                var le = t.FindLessThanOrEqualTo(kd);
                var gt = t.FindGreaterThan(kd);

                var node = t.Min();

                double lek = le != null ? le.Value : int.MinValue;
                double gtk = gt != null ? gt.Value : int.MaxValue;


                if (node.Value > kd)
                {
                    Assert.IsNull(le);
                    Assert.IsNotNull(gt);
                    Assert.AreEqual(gt, node);
                }
                else
                {
                    var succ = node;
                    do
                    {
                        node = succ;
                        succ = t.GetNextNode(node);
                    } while (succ != null && succ.Value <= kd);

                    Assert.AreEqual(node, le);
                    Assert.AreEqual(succ, gt);
                }
            }

            // Remove elements from the tree
            for (int M = k.Length; M > 0; M--)
            {
                int j = rand.Next() % M;
                int i;
                for (i = 0; i < k.Length; i++)
                    if (k[i] >= 0)
                        if (j-- == 0)
                            break;

                if (i >= k.Length)
                    Assert.Fail();

                int kd = k[i];

                var node = t.Find(kd);
                Assert.IsNotNull(node);

                node = t.Remove(node);
                Assert.IsTrue(t.check());

                k[i] = -1 - k[i];
            }

            // The tree should be empty
            Assert.AreEqual(0, t.Count);
        }
Пример #58
0
		public void TestAddBug ()
		{
			var tree = new RedBlackTree<TestNode> ();
			TestNode t1 = new TestNode (1);
			TestNode t2 = new TestNode (2);
			TestNode t3 = new TestNode (3);
			
			tree.Add (t1);
			tree.Add (t2);
			tree.Add (t3);
			Assert.AreEqual (3, tree.Count);
		} 
Пример #59
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);
        }
Пример #60
0
        public void IsEmptyExample()
        {
            var tree = new RedBlackTree<string, int>();

            // Tree is empty.
            Assert.IsTrue(tree.IsEmpty);

            // Add a cat.
            tree.Add(new KeyValuePair<string, int>("cat", 1));

            // Tree is not empty.
            Assert.IsFalse(tree.IsEmpty);

            // Clear the tree - thereby removing all items contained.
            tree.Clear();

            // Tree is empty again with count = 0.
            Assert.IsTrue(tree.IsEmpty);
        }