Пример #1
0
            public void NeedBalancingLL()
            {
                var tree = new RedBlackTree();

                tree.Insert(5);
                tree.Insert(4);
                tree.Insert(3);
                tree.Insert(2);
                tree.Insert(1);
                Assert.True(tree.Contains(1));
                Assert.True(tree.Contains(2));
                Assert.True(tree.Contains(3));
                Assert.True(tree.Contains(4));
                Assert.True(tree.Contains(5));

                Assert.Equal(4, tree._root.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Color);
                Assert.Equal(2, tree._root.Left.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Left.Color);
                Assert.Equal(5, tree._root.Right.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Right.Color);
                Assert.Equal(1, tree._root.Left.Left.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Left.Left.Color);
                Assert.Equal(3, tree._root.Left.Right.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Left.Right.Color);
            }
Пример #2
0
        public void Contains_EmptyTree_ReturnsFalse()
        {
            var tree = new RedBlackTree <int>();

            tree.Contains(5).Should().BeFalse();
            tree.Contains(-12).Should().BeFalse();
        }
Пример #3
0
            public void NeedBalancingLR()
            {
                var tree = new RedBlackTree();

                tree.Insert(1);
                tree.Insert(2);
                tree.Insert(5);
                tree.Insert(3);
                // https://neerc.ifmo.ru/wiki/index.php?title=%D0%9A%D1%80%D0%B0%D1%81%D0%BD%D0%BE-%D1%87%D0%B5%D1%80%D0%BD%D0%BE%D0%B5_%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE
                // SimpleBalancing - без поворотов
                // rrBalancing, значит нужно балансировать ноду которая правая для родителя и у родитель которой также правый для своего родителя(первая r - правость родителя, вторая - ноды)
                tree.Insert(4);
                Assert.True(tree.Contains(1));
                Assert.True(tree.Contains(2));
                Assert.True(tree.Contains(3));
                Assert.True(tree.Contains(4));
                Assert.True(tree.Contains(5));

                Assert.Equal(2, tree._root.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Color);
                Assert.Equal(1, tree._root.Left.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Left.Color);
                Assert.Equal(4, tree._root.Right.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Right.Color);
                Assert.Equal(3, tree._root.Right.Left.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Right.Left.Color);
                Assert.Equal(5, tree._root.Right.Right.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Right.Right.Color);
            }
Пример #4
0
        public void Contains_CorrectReturn()
        {
            var tree = new RedBlackTree <int>();

            tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            tree.Contains(3).Should().BeTrue();
            tree.Contains(7).Should().BeTrue();
            tree.Contains(24).Should().BeFalse();
            tree.Contains(-1).Should().BeFalse();
        }
Пример #5
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));
        }
Пример #6
0
        public void TestContains()
        {
            var testTree = new RedBlackTree <int>();
            var hasOne   = testTree.Contains(1);

            Assert.AreEqual(false, hasOne);

            testTree.Insert(1);
            var hasOneAfterInsert = testTree.Contains(1);

            Assert.AreEqual(true, hasOneAfterInsert);
        }
Пример #7
0
            public void InsertInRoot__InRightRootChild()
            {
                var tree = new RedBlackTree();

                tree.Insert(1);
                tree.Insert(2);
                Assert.True(tree.Contains(1));
                Assert.True(tree.Contains(2));

                Assert.Equal(1, tree._root.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Color);
                Assert.Equal(2, tree._root.Right.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Right.Color);
            }
Пример #8
0
            public void MassInsert__MassDelete()
            {
                var insert = Enumerable.Range(0, 1000).ToArray();
                var delete = insert.Take(100).ToArray();
                var tree   = new RedBlackTree();

                foreach (var item in insert)
                {
                    tree.Insert(item);
                    tree.Insert(item);
                }

                foreach (var item in delete)
                {
                    tree.Remove(item);
                }

                foreach (var item in insert.Except(delete))
                {
                    Assert.True(tree.Contains(item));
                }

                foreach (var item in tree)
                {
                    _testOutputHelper.WriteLine(item.ToString());
                }

                Assert.True(tree.IsValid());
            }
Пример #9
0
        public void Remove_Case3_TreeStillValid()
        {
            // Move to case 6
            var tree = new RedBlackTree <int>();

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

            // Move to case 5
            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 8, 3, 2, 0, 9, 4, 7, 6, 1, 5 });
            tree.Remove(8);
            tree.Remove(6);
            tree.Remove(9);
            tree.Count.Should().Be(7);
            tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 5, 7 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 5, 4, 7 }).Should().BeTrue();

            // Move to case 4
            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 7, 5, 8, 4, 6, 3, 2, 9, 0, 1 });
            tree.Remove(9);
            tree.Remove(6);
            tree.Remove(5);
            tree.Remove(8);
            tree.Count.Should().Be(6);
            tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 7 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 7, 4 }).Should().BeTrue();
        }
Пример #10
0
        public void Remove_Case5_TreeStillValid()
        {
            var tree = new RedBlackTree <int>();

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

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

            tree = new RedBlackTree <int>();
            tree.AddRange(new[] { 7, 0, 1, 4, 8, 2, 3, 6, 5, 9 });
            tree.Remove(7);
            tree.Remove(0);
            tree.Remove(1);
            tree.Remove(4);
            tree.Remove(8);
            tree.GetKeysInOrder().SequenceEqual(new[] { 2, 3, 5, 6, 9 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 2, 6, 5, 9 }).Should().BeTrue();
        }
Пример #11
0
            public void InsertInRoot()
            {
                var tree = new RedBlackTree();

                tree.Insert(1);
                Assert.True(tree.Contains(1));
            }
Пример #12
0
        public void Test_Delete()
        {
            var bst = new RedBlackTree <Byte, Char>();

            bst.Add(1, 'A');
            bst.Delete(1);

            Assert.False(bst.Contains(1));
        }
Пример #13
0
        public void ContainsTest()
        {
            var        target   = new RedBlackTree <int, GenericParameterHelper>();
            var        item     = new GenericParameterHelper(5);
            const bool expected = false;
            bool       actual   = target.Contains(item);

            Assert.AreEqual(expected, actual);
        }
Пример #14
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")));
        }
Пример #15
0
        /// <summary>
        ///A test for Contains
        ///</summary>
        public void ContainsTestHelper <TKey, T>(TKey key, T testItem)
            where T : class
            where TKey : IComparable, IComparable <TKey>, IEquatable <TKey>
        {
            RedBlackTree <TKey, T> target = new RedBlackTree <TKey, T>();
            T          item     = testItem;
            const bool expected = false;
            bool       actual   = target.Contains(item);

            Assert.AreEqual(expected, actual);
        }
Пример #16
0
        public void Remove_Case1_TreeStillValid()
        {
            var tree = new RedBlackTree <int>();

            tree.AddRange(new[] { 5, 2, 8, 1 });
            tree.Remove(1);
            tree.Remove(2);
            tree.Contains(2).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue();
        }
Пример #17
0
    public void Insert_MultipleElements_ShouldHaveQuickFind()
    {
        RedBlackTree <int> rbt = new RedBlackTree <int>();

        for (int i = 0; i < 100000; i++)
        {
            rbt.Insert(i);
        }

        Assert.AreEqual(true, rbt.Contains(99999));
    }
Пример #18
0
        public void ContainsExample()
        {
            // 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)
            };

            // The tree should contain 1 cat and 2 dogs...
            Assert.IsTrue(tree.Contains(new KeyValuePair <string, int>("cat", 1)));

            Assert.IsTrue(tree.Contains(new KeyValuePair <string, int>("dog", 2)));

            // But not 3 cats and 1 dog
            Assert.IsFalse(tree.Contains(new KeyValuePair <string, int>("cat", 3)));

            Assert.IsFalse(tree.Contains(new KeyValuePair <string, int>("dog", 1)));
        }
Пример #19
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);
        }
Пример #20
0
            public void NeedSimpleBalancing1()
            {
                var tree = new RedBlackTree();

                tree.Insert(100);
                tree.Insert(200);
                tree.Insert(50);
                tree.Insert(75);
                tree.Insert(25);
                tree.Insert(20);
                Assert.True(tree.Contains(100));
                Assert.True(tree.Contains(200));
                Assert.True(tree.Contains(50));
                Assert.True(tree.Contains(75));
                Assert.True(tree.Contains(25));
                Assert.True(tree.Contains(20));

                Assert.Equal(100, tree._root.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Color);
                Assert.Equal(50, tree._root.Left.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Left.Color);
                Assert.Equal(200, tree._root.Right.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Right.Color);
                Assert.Equal(25, tree._root.Left.Left.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Left.Left.Color);
                Assert.Equal(75, tree._root.Left.Right.Value);
                Assert.Equal(RedBlackTree.Color.Black, tree._root.Left.Right.Color);
                Assert.Equal(20, tree._root.Left.Left.Left.Value);
                Assert.Equal(RedBlackTree.Color.Red, tree._root.Left.Left.Left.Color);
            }
Пример #21
0
        public void Remove_Case4_TreeStillValid()
        {
            var tree = new RedBlackTree <int>();

            tree.AddRange(new[] { 5, 2, 8, 1, 4, 7, 9, 0, 3 });
            tree.Remove(0);
            tree.Remove(3);
            tree.Remove(2);
            tree.Count.Should().Be(6);
            tree.Contains(2).Should().BeFalse();
            tree.GetKeysInOrder().SequenceEqual(new[] { 1, 4, 5, 7, 8, 9 }).Should().BeTrue();
            tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 1, 8, 7, 9 }).Should().BeTrue();
        }
Пример #22
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();
        }
Пример #23
0
        public void SortedElementsAfterAddingAndRemoving()
        {
            var tree = new RedBlackTree <int>();

            int elementsCount = 100000;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            for (int i = 7; i > 0; i -= 2)
            {
                int el = 0;
                while (el < elementsCount)
                {
                    if (!tree.Contains(el))
                    {
                        tree.Add(el);
                    }
                    el += i;
                }
            }

            bool removedEverything = true;

            //Removing every second number
            for (int i = 0; i < elementsCount; i += 2)
            {
                if (!tree.Remove(i))
                {
                    removedEverything = false;
                }
            }


            int  last              = -1;
            int  count             = 0;
            bool elementsAreSorted = true;

            foreach (var item in tree)
            {
                if (last > item)
                {
                    elementsAreSorted = false;
                }
                last = item;
                count++;
            }

            Assert.IsTrue(tree.Count == count &&
                          elementsAreSorted &&
                          removedEverything);
        }
Пример #24
0
        public void TestRemoveRoot()
        {
            var testTree        = new RedBlackTree <int>();
            var initialSize     = testTree.Size;
            var initialContains = testTree.Contains(4);

            Assert.AreEqual(0, initialSize);
            Assert.AreEqual(false, initialContains);

            testTree.Insert(4);
            var oneSize      = testTree.Size;
            var fourContains = testTree.Contains(4);

            Assert.AreEqual(1, oneSize);
            Assert.AreEqual(true, fourContains);

            testTree.Remove(4);
            var twoSize = testTree.Size;
            var fourContainsAfterRemove = testTree.Contains(4);

            Assert.AreEqual(0, twoSize);
            Assert.AreEqual(false, fourContainsAfterRemove);
        }
Пример #25
0
        public void RemoveRootEveryTimeUntilTreeElementsAreHalfed()
        {
            var tree = new RedBlackTree <int>();

            int elementsCount = 100000;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            for (int i = 7; i > 0; i -= 2)
            {
                int el = 0;
                while (el < elementsCount)
                {
                    if (!tree.Contains(el))
                    {
                        tree.Add(el);
                    }
                    el += i;
                }
            }

            bool removedEverything = true;

            while (tree.Count > elementsCount / 2)
            {
                if (!tree.Remove(tree.Root.Value))
                {
                    removedEverything = false;
                }
            }

            int  last              = -1;
            int  count             = 0;
            bool elementsAreSorted = true;

            foreach (var item in tree)
            {
                if (last > item)
                {
                    elementsAreSorted = false;
                }
                last = item;
                count++;
            }

            Assert.IsTrue(tree.Count == count &&
                          elementsAreSorted &&
                          count == elementsCount / 2 &&
                          removedEverything);
        }
Пример #26
0
        public override void Solve(IOManager io)
        {
            var n = io.ReadInt();

            var rbTree = new RedBlackTree <int>();


            for (int i = 0; i < n; i++)
            {
                rbTree.Add(io.ReadInt());
            }

            var first  = rbTree.Min;
            var second = rbTree.Max;

            rbTree.Remove(first);
            rbTree.Remove(second);

            var last2 = first;
            var last1 = second;

            while (rbTree.Count > 0)
            {
                var next = last2 ^ last1;

                if (rbTree.Contains(next))
                {
                    last2 = last1;
                    last1 = next;
                    rbTree.Remove(next);
                }
                else
                {
                    io.WriteLine("No");
                    return;
                }
            }

            if ((last2 ^ last1) == first && (last1 ^ first) == second)
            {
                io.WriteLine("Yes");
            }
            else
            {
                io.WriteLine("No");
            }
        }
Пример #27
0
        public void RedBlackTreeRemoveTest()
        {
            // inserting and then removing elements
            RedBlackTree <Int32, String> tree = new RedBlackTree <Int32, String>();
            String value;

            foreach (KeyValuePair <Int32, String> keyValuePair in this.values)
            {
                tree.Insert(keyValuePair.Key, keyValuePair.Value);
                tree.Height.ShouldBeLessThanOrEqualTo(20);
            }

            for (Int32 number = -1000; number < 1000; number++)
            {
                tree.Remove(number).ShouldBe(this.values.Select(keyValuePair => keyValuePair.Key).Contains(number));
                tree.Height.ShouldBeLessThanOrEqualTo(20);
            }

            tree.Height.ShouldBe(-1);
            tree.Count.ShouldBe(0);

            foreach (KeyValuePair <Int32, String> keyValuePair in this.values)
            {
                tree.Insert(keyValuePair.Key, keyValuePair.Value);
                tree.Height.ShouldBeLessThanOrEqualTo(20);
            }

            tree.Clear();

            tree.Height.ShouldBe(-1);
            tree.Count.ShouldBe(0);

            foreach (KeyValuePair <Int32, String> keyValuePair in this.values)
            {
                tree.Contains(keyValuePair.Key).ShouldBeFalse();
                tree.TrySearch(keyValuePair.Key, out value).ShouldBeFalse();
            }

            // exceptions
            RedBlackTree <Object, String> objectTree = new RedBlackTree <Object, String>();

            Should.Throw <ArgumentNullException>(() => objectTree.Remove(null));
        }
Пример #28
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")));
        }
Пример #29
0
            public void MassInsert()
            {
                var data = Enumerable.Range(0, 1000).ToArray();
                var tree = new RedBlackTree();

                foreach (var item in data)
                {
                    tree.Insert(item);
                }

                foreach (var item in data)
                {
                    Assert.True(tree.Contains(item));
                }

                foreach (var item in tree)
                {
                    _testOutputHelper.WriteLine(item.ToString());
                }

                Assert.True(tree.IsValid());
            }
Пример #30
0
        public void RedBlackTreeInsertTest()
        {
            RedBlackTree <Int32, String> tree = new RedBlackTree <Int32, String>();
            String value;

            // insert elements
            foreach (KeyValuePair <Int32, String> keyValuePair in this.values)
            {
                tree.Insert(keyValuePair.Key, keyValuePair.Value);
                tree.Height.ShouldBeLessThanOrEqualTo(5); // the maximum height of a Red Black tree is 2*lg(n+1)
            }

            tree.Count.ShouldBe(this.values.Length);
            tree.Height.ShouldBeLessThanOrEqualTo(5);

            foreach (KeyValuePair <Int32, String> keyValuePair in this.values)
            {
                tree.Contains(keyValuePair.Key).ShouldBeTrue();
                tree.Search(keyValuePair.Key).ShouldBe(keyValuePair.Value);

                tree.TrySearch(keyValuePair.Key, out value).ShouldBeTrue();
                value.ShouldBe(keyValuePair.Value);
            }

            // exceptions
            Should.Throw <ArgumentException>(() => tree.Search(-10));
            Should.Throw <ArgumentException>(() =>
            {
                tree.Insert(0, String.Empty);
                tree.Insert(0, String.Empty);
            });

            RedBlackTree <Object, String> objectTree = new RedBlackTree <Object, String>();

            Should.Throw <ArgumentNullException>(() => objectTree.Insert(null, null));
            Should.Throw <ArgumentNullException>(() => objectTree.Contains(null));
            Should.Throw <ArgumentNullException>(() => objectTree.TrySearch(null, out value));
        }
Пример #31
0
        public void RemoveAllExceptOne()
        {
            var tree = new RedBlackTree <int>();

            int elementsCount = 100000;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            for (int i = 7; i > 0; i -= 2)
            {
                int el = 0;
                while (el < elementsCount)
                {
                    if (!tree.Contains(el))
                    {
                        tree.Add(el);
                    }
                    el += i;
                }
            }

            bool removedEverything = true;

            for (int i = 0; i < elementsCount - 1; i++)
            {
                if (!tree.Remove(i))
                {
                    removedEverything = false;
                }
            }

            Assert.IsTrue(tree.Count == 1 &&
                          removedEverything &&
                          tree.Root.Value == elementsCount - 1 &&
                          tree.Root.Left == null &&
                          tree.Root.Right == null);
        }
Пример #32
0
        public void ContainsExample()
        {
            // 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)
                                                 };

            // The tree should contain 1 cat and 2 dogs...
            Assert.IsTrue(tree.Contains(new KeyValuePair<string, int>("cat", 1)));

            Assert.IsTrue(tree.Contains(new KeyValuePair<string, int>("dog", 2)));

            // But not 3 cats and 1 dog
            Assert.IsFalse(tree.Contains(new KeyValuePair<string, int>("cat", 3)));

            Assert.IsFalse(tree.Contains(new KeyValuePair<string, int>("dog", 1)));
        }
        public static void DoTest()
        {
            // Test against the worst case of insertion
            // Case: insert increasing numbers and check if it leads to a linked list
            var redBlackTree = new RedBlackTree<int>(allowDuplicates: false);

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

            Debug.Assert(redBlackTree.Height < redBlackTree.Count, "Fail! Tree doesn't rebalance against sorted elements!");

            Console.WriteLine("********************");
            Console.WriteLine(" [*] RED-BLACK TREE:\r\n");
            Console.WriteLine("********************");
            Console.WriteLine(redBlackTree.DrawTree());
            Console.WriteLine("\r\n");


            //
            // Test against re-shuffled insertions (not like above order)
            redBlackTree = new RedBlackTree<int>(allowDuplicates: false);

            redBlackTree.Insert(4);
            redBlackTree.Insert(5);
            redBlackTree.Insert(7);
            redBlackTree.Insert(2);
            redBlackTree.Insert(1);
            redBlackTree.Insert(3);
            redBlackTree.Insert(6);
            redBlackTree.Insert(0);
            redBlackTree.Insert(8);
            redBlackTree.Insert(10);
            redBlackTree.Insert(9);

            //
            // ASSERT INSERTING DUPLICATES WOULD BREAK
            var insert_duplicate_passed = true;
            try
            {
                // 2 already exists in tree
                redBlackTree.Insert(2);
                insert_duplicate_passed = true;
            }
            catch
            {
                insert_duplicate_passed = false;
            }

            Debug.Assert(insert_duplicate_passed == false, "Fail! The tree doesn't allow duplicates");


            //
            // PRINT TREE
            Console.WriteLine("********************");
            Console.WriteLine(" [*] RED-BLACK TREE:\r\n");
            Console.WriteLine("********************");
            Console.WriteLine(redBlackTree.DrawTree());
            Console.WriteLine("\r\n");


            // Assert count
            Debug.Assert(redBlackTree.Count == 11);

            // Assert existence and nonexistence of some items
            Debug.Assert(redBlackTree.Contains(1) == true);
            Debug.Assert(redBlackTree.Contains(3) == true);
            Debug.Assert(redBlackTree.Contains(999) == false);

            // ASSERT THAT EACH LEVEL HAS A DIFFERENT COLOR
            Asset_Levels_Different_Colors(redBlackTree);

            // Do some deletions
            redBlackTree.Remove(7);
            redBlackTree.Remove(1);
            redBlackTree.Remove(3);

            // Assert count
            Debug.Assert(redBlackTree.Count == 8);

            // Assert nonexistence of previously existing items
            Debug.Assert(redBlackTree.Contains(1) == false);
            Debug.Assert(redBlackTree.Contains(3) == false);

            // Remove root value
            var oldRootVal = redBlackTree.Root.Value;
            redBlackTree.Remove(redBlackTree.Root.Value);

            // Assert count
            Debug.Assert(redBlackTree.Count == 7);

            // Assert nonexistence of old root's value
            Debug.Assert(redBlackTree.Contains(oldRootVal) == false);


            //
            // PRINT TREE
            Console.WriteLine("********************");
            Console.WriteLine(" [*] RED-BLACK TREE:\r\n");
            Console.WriteLine("********************");
            Console.WriteLine(redBlackTree.DrawTree());
            Console.WriteLine("\r\n");

            Console.ReadLine();
        }//end-do-test
Пример #34
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);
        }
Пример #35
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);
        }