public void AdditionalTest()
            {
                Queue queue = new QueueArray(3);

                queue.Enqueue(5);
                queue.Enqueue(7);
                queue.Enqueue(9);
                queue.Enqueue(11);
                Assert.AreEqual(5, queue.Peek());
                Assert.AreEqual(5, queue.Dequeue());

                queue.Enqueue(13);
                Assert.AreEqual(7, queue.Peek());
                queue.Enqueue(15);
                Assert.AreEqual(7, queue.Peek());
                Assert.AreEqual(7, queue.Dequeue());
                Assert.AreEqual(9, queue.Dequeue());

                queue.Enqueue(17);
                Assert.AreEqual(11, queue.Peek());
                queue.Enqueue(19);
                queue.Enqueue(21);
                Assert.AreEqual(11, queue.Peek());

                queue.Enqueue(23);
                Assert.AreEqual(11, queue.Dequeue());
                Assert.AreEqual(13, queue.Dequeue());
                Assert.AreEqual(15, queue.Dequeue());
                Assert.AreEqual(17, queue.Dequeue());
                Assert.AreEqual(19, queue.Dequeue());
                Assert.AreEqual(21, queue.Dequeue());
                Assert.AreEqual(23, queue.Dequeue());
            }
Exemplo n.º 2
0
        public void QueueArray_Basic()
        {
            QueueArray <int> queue = new QueueArray <int>();

            queue.Enqueue(0);
            queue.Enqueue(1);
            queue.Enqueue(2);
            CollectionAssert.AreEqual(new int[] { 0, 1, 2 }, queue.ToArray());
            Assert.AreEqual(3, queue.Count);
            Assert.AreEqual(0, queue[0]);
            Assert.AreEqual(1, queue[1]);
            Assert.AreEqual(2, queue[2]);

            Assert.AreEqual(0, queue.Peek());
            Assert.AreEqual(3, queue.Count);

            Assert.AreEqual(0, queue.Dequeue());
            CollectionAssert.AreEqual(new int[] { 1, 2 }, queue.ToArray());
            Assert.AreEqual(2, queue.Count);
            Assert.AreEqual(1, queue[0]);
            Assert.AreEqual(2, queue[1]);

            Assert.AreEqual(1, queue.Dequeue());
            CollectionAssert.AreEqual(new int[] { 2 }, queue.ToArray());
            Assert.AreEqual(1, queue.Count);
            Assert.AreEqual(2, queue[0]);

            Assert.AreEqual(2, queue.Dequeue());
            CollectionAssert.AreEqual(new int[] { }, queue.ToArray());
            Assert.AreEqual(0, queue.Count);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Begins an asynchronous operation to receive a channel request (using a specified timeout).
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="timeout">The <see cref="TimeSpan" /> value specifying the maximum time to wait for a request.</param>
        /// <param name="callback">The <see cref="AsyncCallback" /> delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application specific state (or <c>null</c>).</param>
        /// <returns>The <see cref="IAsyncResult" /> instance to be used to track the status of the operation.</returns>
        /// <remarks>
        /// <note>
        /// All calls to <see cref="BeginReceiveRequest" /> must eventually be followed by a call to <see cref="EndReceiveRequest" />.
        /// </note>
        /// </remarks>
        public IAsyncResult BeginReceiveRequest(ReplyChannel channel, TimeSpan timeout, AsyncCallback callback, object state)
        {
            AsyncResult <RequestInfo, ReplyChannel> arReceive;

            using (TimedLock.Lock(this))
            {
                timeout = ServiceModelHelper.ValidateTimeout(timeout);

                arReceive               = new AsyncResult <RequestInfo, ReplyChannel>(null, callback, state);
                arReceive.TTD           = SysTime.Now + timeout;
                arReceive.InternalState = channel;
                arReceive.Started(ServiceModelHelper.AsyncTrace);

                // Check to see if we already have a queued request.

                if (requestQueue.Count > 0)
                {
                    arReceive.Result = requestQueue.Dequeue();
                    arReceive.Notify();
                    return(arReceive);
                }

                // Otherwise queue the receive operation.

                receiveQueue.Enqueue(arReceive);
                return(arReceive);
            }
        }
            public void EnqueueTest()
            {
                Queue queue = new QueueArray();

                queue.Enqueue(5);
                queue.Enqueue("this");
                queue.Enqueue(15.5);

                object[] outputQueue = getQueueArray(queue);
                Assert.AreEqual(10, outputQueue.Count());
                Assert.AreEqual(5, outputQueue[0]);
                Assert.AreEqual("this", outputQueue[1]);
                Assert.AreEqual(15.5, outputQueue[2]);
                Assert.IsNull(outputQueue[3]);
                Assert.IsNull(outputQueue[9]);


                queue = new QueueArray(3);
                queue.Enqueue(5);
                queue.Enqueue(7);
                queue.Enqueue(9);
                queue.Enqueue(11);
                queue.Enqueue(13);
                outputQueue = getQueueArray(queue);
                Assert.AreEqual(5, outputQueue[0]);
                Assert.AreEqual(7, outputQueue[1]);
                Assert.AreEqual(9, outputQueue[2]);
                Assert.AreEqual(11, outputQueue[3]);
                Assert.AreEqual(13, outputQueue[4]);
                Assert.AreEqual(null, outputQueue[5]);
            }
Exemplo n.º 5
0
        public void TestQueue()
        {
            var queue = new QueueArray <int>();

            queue.Enqueue(10);
            Assert.Equal(1, queue.Count);
            queue.Enqueue(20);
            Assert.Equal(2, queue.Count);
            Assert.False(queue.IsEmpty);
            Assert.Equal(10, queue.Dequeue());
            Assert.Equal(20, queue.Dequeue());
            Assert.True(queue.IsEmpty);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Begins an asynchronous operation to receive a message (using the specified timeout).
        /// </summary>
        /// <param name="timeout">The <see cref="TimeSpan" /> value specifying the maximum time to wait for a message.</param>
        /// <param name="callback">The <see cref="AsyncCallback" /> delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application specific state (or <c>null</c>).</param>
        /// <returns>The <see cref="IAsyncResult" /> instance to be used to track the status of the operation.</returns>
        /// <remarks>
        /// <note>
        /// All calls to <see cref="BeginReceive(TimeSpan,AsyncCallback,object)" /> must eventually be followed by a call to <see cref="EndReceive" />.
        /// </note>
        /// </remarks>
        public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            AsyncResult <Message, object> arReceive;

            using (TimedLock.Lock(this))
            {
                timeout = ServiceModelHelper.ValidateTimeout(timeout);

                arReceive     = new AsyncResult <Message, object>(null, callback, state);
                arReceive.TTD = SysTime.Now + timeout;
                arReceive.Started(ServiceModelHelper.AsyncTrace);

                // Non-open channels always return null

                if (base.State != CommunicationState.Opened)
                {
                    arReceive.Result = null;
                    arReceive.Notify();
                    return(arReceive);
                }

                // Check to see if we already have a queued message.

                if (msgQueue.Count > 0)
                {
                    arReceive.Result = msgQueue.Dequeue();
                    arReceive.Notify();
                    return(arReceive);
                }

                // Setup to return null if the remote side of the connection
                // has been closed.

                if (!session.IsConnected)
                {
                    arReceive.Notify();
                    return(arReceive);
                }

                // Otherwise queue the receive operation.

                receiveQueue.Enqueue(arReceive);
                return(arReceive);
            }
        }
Exemplo n.º 7
0
        public void Enqueue()
        {
            IQueue <Person> queue = new QueueArray <Person>();

            foreach (Person person in RandomTestData)
            {
                queue.Enqueue(person);
            }
        }
Exemplo n.º 8
0
        public void EnqueueWithCapacity()
        {
            IQueue <Person> queue = new QueueArray <Person>(RandomTestData.Length);

            foreach (Person person in RandomTestData)
            {
                queue.Enqueue(person);
            }
        }
Exemplo n.º 9
0
        [TestMethod] public void Enqueue_Dequeue_Testing()
        {
            void Test <T>(T[] values)
            {
                Towel.Sort.Shuffle(values);
                IQueue <T> queue = new QueueArray <T>();

                values.Stepper(x => queue.Enqueue(x));
                values.Stepper(x => x.Equals(queue.Dequeue()));
            }
Exemplo n.º 10
0
        [TestMethod] public void Enqueue_Dequeue_Testing()
        {
            void Test <T>(T[] values)
            {
                Towel.Algorithms.Sort.Shuffle(values);
                IQueue <T> stack = new QueueArray <T>();

                values.Stepper(x => stack.Enqueue(x));
                values.Stepper(x => x.Equals(stack.Dequeue()));
            }
Exemplo n.º 11
0
        public void EnqueueWithCapacity()
        {
            IQueue <int> queue        = new QueueArray <int>(EnqueueCount);
            int          enqueueCount = EnqueueCount;

            for (int i = 0; i < enqueueCount; i++)
            {
                queue.Enqueue(i);
            }
        }
        public void QueueSizeIncreases()
        {
            var queue = new QueueArray <int>();
            var size  = 100;

            for (int i = 0; i < size; i++)
            {
                queue.Enqueue(i);
            }

            Assert.AreEqual(size, queue.Size());
        }
        public void MultipleEnqueueDequeueReturnValues()
        {
            var queue = new QueueArray <int>();
            var size  = 50;

            for (int i = 0; i < size; i++)
            {
                queue.Enqueue(i);
            }

            for (int i = 0; i < size; i++)
            {
                var dequeued = queue.Dequeue();
                Assert.AreEqual(i, dequeued);
            }
        }
        public void StackSizeDecreases()
        {
            var queue = new QueueArray <int>();
            var size  = 100;

            for (int i = 0; i < size; i++)
            {
                queue.Enqueue(i);
            }

            for (int i = 0; i < size; i++)
            {
                queue.Dequeue();
            }

            Assert.AreEqual(0, queue.Size());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Begins an asynchronous operation to wait for a specified period of time for a message to be received
        /// for a channel.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="timeout">The maximum <see cref="TimeSpan" /> to wait.</param>
        /// <param name="callback">The <see cref="AsyncCallback" /> delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application specific state (or <c>null</c>).</param>
        /// <returns>The <see cref="IAsyncResult" /> instance to be used to track the status of the operation.</returns>
        /// <remarks>
        /// All successful calls to <see cref="BeginWaitForMessage" /> must eventually be followed by a call to <see cref="EndWaitForMessage" />.
        /// </remarks>
        public IAsyncResult BeginWaitForMessage(InputChannel channel, TimeSpan timeout, AsyncCallback callback, object state)
        {
            AsyncResult <bool, InputChannel> arWait;

            using (TimedLock.Lock(this))
            {
                timeout = ServiceModelHelper.ValidateTimeout(timeout);

                arWait               = new AsyncResult <bool, InputChannel>(null, callback, state);
                arWait.TTD           = SysTime.Now + timeout;
                arWait.InternalState = channel;
                arWait.Started(ServiceModelHelper.AsyncTrace);

                // Non-open channels always return false.

                if (base.State != CommunicationState.Opened)
                {
                    arWait.Notify();
                    return(arWait);
                }

                // If we already have a queued message, dequeue it and add it to the
                // channel's message queue, so a subsequent call Receive() on the channel
                // will be assured to succeed.  Then notify that the operation is complete.

                if (msgQueue.Count > 0)
                {
                    channel.Enqueue(msgQueue.Dequeue());

                    arWait.Result = true;
                    arWait.Notify();
                    return(arWait);
                }

                // Otherwise queue the wait operation.

                waitQueue.Enqueue(arWait);
                return(arWait);
            }
        }
        public void QueueUnderflow()
        {
            var queue = new QueueArray <int>();
            var size  = 1000;

            for (int i = 0; i < size; i++)
            {
                queue.Enqueue(i);
            }

            for (int i = 0; i < size; i++)
            {
                queue.Dequeue();
            }

            try
            {
                queue.Dequeue();
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual("The Queue is empty.", ex.Message);
            }
        }
Exemplo n.º 17
0
        public void QueueArray_Enumerate()
        {
            QueueArray <int> queue = new QueueArray <int>();
            List <int>       list  = new List <int>();

            queue.Enqueue(0);
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);

            foreach (int value in queue)
            {
                list.Add(value);
            }

            CollectionAssert.AreEqual(new int[] { 0, 1, 2, 3, 4, 5 }, list.ToArray());
        }
Exemplo n.º 18
0
        public void QueueArray_RemoveAt()
        {
            QueueArray <int> queue = new QueueArray <int>();

            queue.Enqueue(0);
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);

            queue.RemoveAt(0);
            CollectionAssert.AreEqual(new int[] { 1, 2, 3, 4, 5 }, queue.ToArray());

            queue.RemoveAt(queue.Count - 1);
            CollectionAssert.AreEqual(new int[] { 1, 2, 3, 4 }, queue.ToArray());

            queue.RemoveAt(2);
            CollectionAssert.AreEqual(new int[] { 1, 2, 4 }, queue.ToArray());
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            try
            {
                var queue = new QueueArray <int>();
                queue.Enqueue(4);
                queue.Enqueue(5);
                queue.Enqueue(6);
                Console.WriteLine(queue.Front + " " + queue.Rear + " " + queue.Size);
                Console.WriteLine(queue.IsFull());

                queue.Enqueue(33);
                queue.Enqueue(33);
                queue.Enqueue(33);
                Console.WriteLine("----------------");
                queue.PrintQueue();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 20
0
        static void Main()
        {
            Random random = new Random();
            int    test   = 10;

            Console.WriteLine("You are runnning the Data Structures example.");
            Console.WriteLine("======================================================");
            Console.WriteLine();

            #region Link (aka Tuple)

            Console.WriteLine("  Link------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    A \"Link\" is like a System.Tuple that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. A Link/Tuple is");
            Console.WriteLine("    used when you have a small, known-sized set of objects");
            Console.WriteLine("    that you want to bundle together without making a custom");
            Console.WriteLine("    custom class.");
            Console.WriteLine();

            Link link = new Link <int, int, int, int, int, int>(0, 1, 2, 3, 4, 5);
            Console.Write("    Traversal: ");
            link.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    Size: {link.Size}");
            Console.WriteLine();

            #endregion

            #region Array

            Console.WriteLine("  Array---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An Array<T> is just a wrapper for arrays that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. An array is used when");
            Console.WriteLine("    dealing with static-sized, known-sized sets of data. Arrays");
            Console.WriteLine("    can be sorted along 1 dimensions for binary searching algorithms.");
            Console.WriteLine();

            IArray <int> array = new Array <int>(test);

            Console.Write($"    Filling in (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                array[i] = i;
            }
            Console.WriteLine();

            Console.Write("    Traversal: ");
            array.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    Length: {array.Length}");

            Console.WriteLine();

            #endregion

            #region List

            Console.WriteLine("  List---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An List is like an IList that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. \"ListArray\" is");
            Console.WriteLine("    the array implementation while \"ListLinked\" is the");
            Console.WriteLine("    the linked-list implementation. An List is used");
            Console.WriteLine("    when dealing with an unknown quantity of data that you");
            Console.WriteLine("    will likely have to enumerate/step through everything. The");
            Console.WriteLine("    ListArray shares the properties of an Array in");
            Console.WriteLine("    that it can be relateively quickly sorted along 1 dimensions");
            Console.WriteLine("    for binary search algorithms.");
            Console.WriteLine();

            // ListArray ---------------------------------------
            IList <int> listArray = new ListArray <int>(test);

            Console.Write($"    [ListArray] Adding (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                listArray.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListArray] Traversal: ");
            listArray.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    [ListArray] Count: {listArray.Count}");

            listArray.Clear();

            Console.WriteLine();

            // ListLinked ---------------------------------------
            IList <int> listLinked = new ListLinked <int>();

            Console.Write($"    [ListLinked] Adding (0-{test - 1})...");
            for (int i = 0; i < test; i++)
            {
                listLinked.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListLinked] Traversal: ");
            listLinked.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine($"    [ListLinked] Count: {listLinked.Count}");

            listLinked.Clear();

            Console.WriteLine();

            #endregion

            #region Stack
            {
                Console.WriteLine("  Stack---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Stack\" is a Stack that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"StackArray\" is");
                Console.WriteLine("    the array implementation while \"StackLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Push");
                Console.WriteLine("    and Pop functions.");
                Console.WriteLine();

                IStack <int> stackArray = new StackArray <int>();

                Console.Write($"    [StackArray] Pushing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    stackArray.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackArray] Traversal: ");
                stackArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Peek: {stackArray.Peek()}");
                Console.WriteLine($"    [StackArray] Pop: {stackArray.Pop()}");
                Console.WriteLine($"    [StackArray] Count: {stackArray.Count}");

                stackArray.Clear();

                Console.WriteLine();

                IStack <int> stackLinked = new StackLinked <int>();

                Console.Write($"    [StackLinked] Pushing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    stackLinked.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackLinked] Traversal: ");
                stackLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Peek: {stackLinked.Peek()}");
                Console.WriteLine($"    [StackLinked] Pop: {stackLinked.Pop()}");
                Console.WriteLine($"    [StackLinked] Count: {stackLinked.Count}");

                stackLinked.Clear();

                Console.WriteLine();
            }
            #endregion

            #region Queue
            {
                Console.WriteLine("  Queue---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Queue\" is a Queue that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"QueueArray\" is");
                Console.WriteLine("    the array implementation while \"QueueLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Queue/Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Queue");
                Console.WriteLine("    and Dequeue functions.");
                Console.WriteLine();

                IQueue <int> queueArray = new QueueArray <int>();

                Console.Write($"    [QueueArray] Enqueuing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    queueArray.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueArray] Traversal: ");
                queueArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Peek: {queueArray.Peek()}");
                Console.WriteLine($"    [QueueArray] Dequeue: {queueArray.Dequeue()}");
                Console.WriteLine($"    [QueueArray] Count: {queueArray.Count}");

                queueArray.Clear();

                Console.WriteLine();

                IQueue <int> queueLinked = new QueueLinked <int>();

                Console.Write($"    [QueueLinked] Enqueuing (0-{test - 1})...");
                for (int i = 0; i < test; i++)
                {
                    queueLinked.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueLinked] Traversal: ");
                queueLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Peek: {queueLinked.Peek()}");
                Console.WriteLine($"    [QueueLinked] Pop: {queueLinked.Dequeue()}");
                Console.WriteLine($"    [QueueLinked] Count: {queueLinked.Count}");

                queueLinked.Clear();

                Console.WriteLine();
            }
            #endregion

            #region Heap
            {
                Console.WriteLine("  Heap---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Heap\" is a binary tree that stores items based on priorities.");
                Console.WriteLine("    It implements Towel.DataStructures.DataStructure like the others.");
                Console.WriteLine("    It uses sifting algorithms to move nodes vertically through itself.");
                Console.WriteLine("    It is often the best data structure for standard priority queues.");
                Console.WriteLine("    \"HeapArray\" is an implementation where the tree has been flattened");
                Console.WriteLine("    into an array.");
                Console.WriteLine();

                Console.WriteLine("    Let's say the priority is how close a number is to \"5\".");
                Console.WriteLine("    So \"Dequeue\" will give us the next closest value to \"5\".");
Exemplo n.º 21
0
        public void Should_Peek_First_Element()
        {
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(4);

            Assert.AreEqual(1, _queue.Peek());
        }
Exemplo n.º 22
0
        public void Test()
        {
            var queue = new QueueArray <int>();

            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);

            Assert.AreEqual("12345", queue.GetValues());

            Assert.AreEqual(1, queue.Dequeue());
            Assert.AreEqual("2345", queue.GetValues());

            Assert.AreEqual(2, queue.Dequeue());
            Assert.AreEqual("345", queue.GetValues());

            queue.Enqueue(6);
            Assert.AreEqual("3456", queue.GetValues());

            queue.Enqueue(7);
            Assert.AreEqual("34567", queue.GetValues());

            queue.Enqueue(8);
            Assert.AreEqual("345678", queue.GetValues());

            queue.Enqueue(9);
            Assert.AreEqual("3456789", queue.GetValues());

            queue.Enqueue(1);
            Assert.AreEqual("34567891", queue.GetValues());

            queue.Enqueue(2);
            Assert.AreEqual("345678912", queue.GetValues());
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Random random = new Random();
            int    test   = 10;

            Console.WriteLine("You are runnning the Data Structures example.");
            Console.WriteLine("======================================================");
            Console.WriteLine();

            #region Link (aka Tuple)

            Console.WriteLine("  Link------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    A \"Link\" is like a System.Tuple that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. A Link/Tuple is");
            Console.WriteLine("    used when you have a small, known-sized set of objects");
            Console.WriteLine("    that you want to bundle together without making a custom");
            Console.WriteLine("    custom class.");
            Console.WriteLine();

            Link link = new Link <int, int, int, int, int, int>(0, 1, 2, 3, 4, 5);
            Console.Write("    Traversal: ");
            link.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine("    Size: " + link.Size);
            Console.WriteLine();

            #endregion

            #region Array

            Console.WriteLine("  Array---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An Array<T> is just a wrapper for arrays that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. An array is used when");
            Console.WriteLine("    dealing with static-sized, known-sized sets of data. Arrays");
            Console.WriteLine("    can be sorted along 1 dimensions for binary searching algorithms.");
            Console.WriteLine();

            IArray <int> indexed = new Array <int>(test);

            Console.Write("    Filling in (0-" + (test - 1) + ")...");
            for (int i = 0; i < test; i++)
            {
                indexed[i] = i;
            }
            Console.WriteLine();

            Console.Write("    Traversal: ");
            indexed.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine("    Length: " + indexed.Length);

            Console.WriteLine();

            #endregion

            #region List

            Console.WriteLine("  List---------------------------------");
            Console.WriteLine();
            Console.WriteLine("    An List is like an IList that implements");
            Console.WriteLine("    Towel.DataStructures.DataStructure. \"ListArray\" is");
            Console.WriteLine("    the array implementation while \"ListLinked\" is the");
            Console.WriteLine("    the linked-list implementation. An List is used");
            Console.WriteLine("    when dealing with an unknown quantity of data that you");
            Console.WriteLine("    will likely have to enumerate/step through everything. The");
            Console.WriteLine("    ListArray shares the properties of an Array in");
            Console.WriteLine("    that it can be relateively quickly sorted along 1 dimensions");
            Console.WriteLine("    for binary search algorithms.");
            Console.WriteLine();

            // ListArray ---------------------------------------
            IList <int> addableArray = new ListArray <int>(test);

            Console.Write("    [ListArray] Adding (0-" + (test - 1) + ")...");
            for (int i = 0; i < test; i++)
            {
                addableArray.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListArray] Traversal: ");
            addableArray.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine("    [ListArray] Count: " + addableArray.Count);

            addableArray.Clear(); // Clears the addable

            Console.WriteLine();

            // ListLinked ---------------------------------------
            IList <int> addableLinked = new ListLinked <int>();

            Console.Write("    [ListLinked] Adding (0-" + (test - 1) + ")...");
            for (int i = 0; i < test; i++)
            {
                addableLinked.Add(i);
            }
            Console.WriteLine();

            Console.Write("    [ListLinked] Traversal: ");
            addableLinked.Stepper(i => Console.Write(i));
            Console.WriteLine();

            Console.WriteLine("    [ListLinked] Count: " + addableLinked.Count);

            addableLinked.Clear(); // Clears the addable

            Console.WriteLine();

            #endregion

            #region Stack
            {
                Console.WriteLine("  Stack---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Stack\" is a Stack that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"StackArray\" is");
                Console.WriteLine("    the array implementation while \"StackLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Push");
                Console.WriteLine("    and Pop functions.");
                Console.WriteLine();

                IStack <int> firstInLastOutArray = new StackArray <int>();

                Console.Write("    [StackArray] Pushing (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    firstInLastOutArray.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackArray] Traversal: ");
                firstInLastOutArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    [StackArray] Pop: " + firstInLastOutArray.Pop());
                Console.WriteLine("    [StackArray] Pop: " + firstInLastOutArray.Pop());
                Console.WriteLine("    [StackArray] Peek: " + firstInLastOutArray.Peek());
                Console.WriteLine("    [StackArray] Pop: " + firstInLastOutArray.Pop());
                Console.WriteLine("    [StackArray] Count: " + firstInLastOutArray.Count);

                firstInLastOutArray.Clear(); // Clears the firstInLastOut

                Console.WriteLine();

                IStack <int> firstInLastOutLinked = new StackLinked <int>();

                Console.Write("    [StackLinked] Pushing (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    firstInLastOutLinked.Push(i);
                }
                Console.WriteLine();

                Console.Write("    [StackLinked] Traversal: ");
                firstInLastOutLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    [StackLinked] Pop: " + firstInLastOutLinked.Pop());
                Console.WriteLine("    [StackLinked] Pop: " + firstInLastOutLinked.Pop());
                Console.WriteLine("    [StackLinked] Peek: " + firstInLastOutLinked.Peek());
                Console.WriteLine("    [StackLinked] Pop: " + firstInLastOutLinked.Pop());
                Console.WriteLine("    [StackLinked] Count: " + firstInLastOutLinked.Count);

                firstInLastOutLinked.Clear(); // Clears the firstInLastOut

                Console.WriteLine();
            }
            #endregion

            #region Queue
            {
                Console.WriteLine("  Queue---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Queue\" is a Queue that implements");
                Console.WriteLine("    Towel.DataStructures.DataStructure. \"QueueArray\" is");
                Console.WriteLine("    the array implementation while \"QueueLinked\" is the");
                Console.WriteLine("    the linked-list implementation. A Queue/Stack is used");
                Console.WriteLine("    specifically when you need the algorithm provided by the Queue");
                Console.WriteLine("    and Dequeue functions.");
                Console.WriteLine();

                IQueue <int> firstInFirstOutArray = new QueueArray <int>();

                Console.Write("    [QueueArray] Enqueuing (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    firstInFirstOutArray.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueArray] Traversal: ");
                firstInFirstOutArray.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue());
                Console.WriteLine("    [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue());
                Console.WriteLine("    [QueueArray] Peek: " + firstInFirstOutArray.Peek());
                Console.WriteLine("    [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue());
                Console.WriteLine("    [QueueArray] Count: " + firstInFirstOutArray.Count);

                firstInFirstOutArray.Clear(); // Clears the firstInLastOut

                Console.WriteLine();

                IQueue <int> firstInFirstOutLinked = new QueueLinked <int>();

                Console.Write("    [QueueLinked] Enqueuing (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    firstInFirstOutLinked.Enqueue(i);
                }
                Console.WriteLine();

                Console.Write("    [QueueLinked] Traversal: ");
                firstInFirstOutLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue());
                Console.WriteLine("    [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue());
                Console.WriteLine("    [QueueLinked] Peek: " + firstInFirstOutLinked.Peek());
                Console.WriteLine("    [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue());
                Console.WriteLine("    [QueueLinked] Count: " + firstInFirstOutLinked.Count);

                firstInFirstOutLinked.Clear(); // Clears the firstInLastOut

                Console.WriteLine();
            }
            #endregion

            #region Heap
            {
                Console.WriteLine("  Heap---------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An \"Heap\" is a binary tree that stores items based on priorities.");
                Console.WriteLine("    It implements Towel.DataStructures.DataStructure like the others.");
                Console.WriteLine("    It uses sifting algorithms to move nodes vertically through itself.");
                Console.WriteLine("    It is often the best data structure for standard priority queues.");
                Console.WriteLine("    \"HeapArray\" is an implementation where the tree has been flattened");
                Console.WriteLine("    into an array.");
                Console.WriteLine();

                Console.WriteLine("    Let's say the priority is how close a number is to \"5\".");
                Console.WriteLine("    So \"Dequeue\" will give us the next closest value to \"5\".");
                CompareResult Priority(int a, int b)
                {
                    int           _a         = Compute.AbsoluteValue(a - 5);
                    int           _b         = Compute.AbsoluteValue(b - 5);
                    CompareResult comparison = Compare.Wrap(_b.CompareTo(_a));

                    return(comparison);
                }

                Console.WriteLine();

                IHeap <int> heapArray = new HeapArray <int>(Priority);

                Console.Write("    [HeapArray] Enqueuing (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    heapArray.Enqueue(i);
                }
                Console.WriteLine();

                Console.WriteLine("    [HeapArray] Dequeue: " + heapArray.Dequeue());
                Console.WriteLine("    [HeapArray] Dequeue: " + heapArray.Dequeue());
                Console.WriteLine("    [HeapArray] Peek: " + heapArray.Peek());
                Console.WriteLine("    [HeapArray] Dequeue: " + heapArray.Dequeue());
                Console.WriteLine("    [HeapArray] Count: " + heapArray.Count);

                heapArray.Clear(); // Clears the heapArray

                Console.WriteLine();
            }
            #endregion

            #region Tree

            //Console.WriteLine("  Tree-----------------------------");

            //Tree<int> tree_Map = new TreeMap<int>(0, Compute.Equal, Hash.Default);

            //for (int i = 1; i < test; i++)
            //{
            //    tree_Map.Add(i, i / Compute.SquareRoot(i));
            //}
            //Console.Write("    Children of 0 (root): ");
            //tree_Map.Children(0, (int i) => { Console.Write(i + " "); });
            //Console.WriteLine();
            //Console.Write("    Children of " + ((int)System.Math.Sqrt(test) - 1) + " (root): ");
            //tree_Map.Children(((int)System.Math.Sqrt(test) - 1), (int i) => { Console.Write(i + " "); });
            //Console.WriteLine();
            //Console.Write("    Traversal: ");
            //tree_Map.Stepper((int i) => { Console.Write(i + " "); });
            //Console.WriteLine();

            //Console.WriteLine();

            #endregion

            #region AVL Tree
            {
                Console.WriteLine("  AvlTree------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An AVL Tree is a sorted binary tree.");
                Console.WriteLine("    It implements Towel.DataStructures.DataStructure like the others.");
                Console.WriteLine("    It allows for very fast 1D ranged queries/traversals.");
                Console.WriteLine("    It is very similar to an Red Black tree, but uses a different sorting algorithm.");
                Console.WriteLine();

                IAvlTree <int> avlTree = new AvlTreeLinked <int>();

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    avlTree.Add(i);
                }
                Console.WriteLine();

                Console.Write("    Traversal: ");
                avlTree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                //// Note: Because the nodes in AVL Tree linked do not have
                //// a parent pointer, the IEnumerable "foreach" iteration
                //// is extremely slow and should be avoided. It requires
                //// a stack for it's iteration.
                //
                //Console.Write("    Traversal Foreach: ");
                //foreach (int i in avlTree)
                //{
                //    Console.Write(i);
                //}
                //Console.WriteLine();

                int minimum = random.Next(1, test / 2);
                int maximum = random.Next(1, test / 2) + test / 2;
                Console.Write("    Ranged Traversal [" + minimum + "-" + maximum + "]: ");
                avlTree.Stepper(i => Console.Write(i), minimum, maximum);
                Console.WriteLine();

                int removal = random.Next(0, test);
                Console.Write("    Remove(" + removal + "): ");
                avlTree.Remove(removal);
                avlTree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int contains = random.Next(0, test);
                Console.WriteLine("    Contains(" + contains + "): " + avlTree.Contains(contains));
                Console.WriteLine("    Current Least: " + avlTree.CurrentLeast);
                Console.WriteLine("    Current Greatest: " + avlTree.CurrentGreatest);
                Console.WriteLine("    Count: " + avlTree.Count);

                avlTree.Clear(); // Clears the AVL tree

                Console.WriteLine();
            }
            #endregion

            #region Red-Black Tree
            {
                Console.WriteLine("  Red-Black Tree------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An Red-Black Tree is a sorted binary tree.");
                Console.WriteLine("    It implements Towel.DataStructures.DataStructure like the others.");
                Console.WriteLine("    It allows for very fast 1D ranged queries/traversals.");
                Console.WriteLine("    It is very similar to an AVL tree, but uses a different sorting algorithm.");
                Console.WriteLine();

                IRedBlackTree <int> redBlackTree = new RedBlackTreeLinked <int>();

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    redBlackTree.Add(i);
                }
                Console.WriteLine();

                Console.Write("    Traversal: ");
                redBlackTree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int minimum = random.Next(1, test / 2);
                int maximum = random.Next(1, test / 2) + test / 2;
                Console.Write("    Ranged Traversal [" + minimum + "-" + maximum + "]: ");
                redBlackTree.Stepper(i => Console.Write(i), minimum, maximum);
                Console.WriteLine();

                int removal = random.Next(0, test);
                Console.Write("    Remove(" + removal + "): ");
                redBlackTree.Remove(removal);
                redBlackTree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int contains = random.Next(0, test);
                Console.WriteLine("    Contains(" + contains + "): " + redBlackTree.Contains(contains));
                Console.WriteLine("    Current Least: " + redBlackTree.CurrentLeast);
                Console.WriteLine("    Current Greatest: " + redBlackTree.CurrentGreatest);
                Console.WriteLine("    Count: " + redBlackTree.Count);

                redBlackTree.Clear(); // Clears the Red Black tree

                Console.WriteLine();
            }
            #endregion

            #region BTree
            {
                Console.WriteLine("  B Tree------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A B Tree is a sorted binary tree that allows multiple values to");
                Console.WriteLine("    be stored per node. This makes it sort of a hybrid between a");
                Console.WriteLine("    binary tree and an array. Because multiple values are stored ");
                Console.WriteLine("    per node, it means less nodes must be traversed to completely");
                Console.WriteLine("    traverse the values in the B tree.");
                Console.WriteLine();

                Console.WriteLine("    The generic B Tree in Towel is still in development.");

                Console.WriteLine();
            }
            #endregion

            #region Set
            {
                Console.WriteLine("  Set------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A Set is like an List, but it does not allow duplicates. Sets are");
                Console.WriteLine("    usually implemented using hash codes. Implementations with hash codes");
                Console.WriteLine("    usually have very fast \"Contains\" checks to see if a value has already");
                Console.WriteLine("    been added to the set.");
                Console.WriteLine();

                ISet <int> setHashLinked = new SetHashLinked <int>();

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    setHashLinked.Add(i);
                }
                Console.WriteLine();

                Console.Write("    Traversal: ");
                setHashLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int a = random.Next(0, test);
                setHashLinked.Remove(a);
                Console.Write("    Remove(" + a + "): ");
                setHashLinked.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int b = random.Next(0, test);
                Console.WriteLine("    Contains(" + b + "): " + setHashLinked.Contains(b));
                Console.WriteLine("    Count: " + setHashLinked.Count);

                Console.WriteLine();
            }
            #endregion

            #region Map (aka Dictionary)
            {
                Console.WriteLine("  Map------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A Map (aka Dictionary) is similar to a Set, but it stores two values (a ");
                Console.WriteLine("    key and a value). Maps do not allow duplicate keys much like Sets don't");
                Console.WriteLine("    allow duplicate values. When provided with the key, the Map uses that key");
                Console.WriteLine("    to look up the value that it is associated with. Thus, it allows you to ");
                Console.WriteLine("    \"map\" one object to another. As with Sets, Maps are usually implemented");
                Console.WriteLine("    using hash codes.");
                Console.WriteLine();

                // Note: the first generic is the value, the second is the key
                IMap <string, int> mapHashLinked = new MapHashLinked <string, int>();

                Console.WriteLine("    Let's map each int to its word representation (ex 1 -> One).");

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    mapHashLinked.Add(i, ((decimal)i).ToEnglishWords());
                }
                Console.WriteLine();

                Console.WriteLine("    Traversal: ");
                mapHashLinked.Keys(i => Console.WriteLine("      " + i + "->" + mapHashLinked[i]));
                Console.WriteLine();

                int a = random.Next(0, test);
                mapHashLinked.Remove(a);
                Console.Write("    Remove(" + a + "): ");
                mapHashLinked.Keys(i => Console.Write(i));
                Console.WriteLine();

                int b = random.Next(0, test);
                Console.WriteLine("    Contains(" + b + "): " + mapHashLinked.Contains(b));
                Console.WriteLine("    Count: " + mapHashLinked.Count);

                Console.WriteLine();
            }
            #endregion

            #region OmnitreePoints
            {
                Console.WriteLine("  OmnitreePoints--------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An Omnitree is an ND SPT that allows for");
                Console.WriteLine("    multidimensional sorting. Any time you need to look");
                Console.WriteLine("    items up based on multiple fields/properties, then");
                Console.WriteLine("    you might want to use an Omnitree. If you need to");
                Console.WriteLine("    perform ranged queries on multiple dimensions, then");
                Console.WriteLine("    the Omnitree is the data structure for you.");
                Console.WriteLine();
                Console.WriteLine("    The \"OmnitreePoints\" stores individual points (vectors),");
                Console.WriteLine("    and the \"OmnitreeBounds\" stores bounded objects (spaces).");
                Console.WriteLine();

                IOmnitreePoints <int, double, string, decimal> omnitree =
                    new OmnitreePointsLinked <int, double, string, decimal>(
                        // This is a location delegate. (how to locate the item along each dimension)
                        (int index, out double a, out string b, out decimal c) =>
                {
                    a = index;
                    b = index.ToString();
                    c = index;
                });

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    omnitree.Add(i);
                }
                Console.WriteLine();

                Console.Write("    Traversal: ");
                omnitree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int    minimumXZ = random.Next(1, test / 2);
                int    maximumXZ = random.Next(1, test / 2) + test / 2;
                string minimumY  = minimumXZ.ToString();
                string maximumY  = maximumXZ.ToString();
                Console.Write("    Spacial Traversal [" +
                              "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" +
                              "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: ");
                omnitree.Stepper(i => Console.Write(i),
                                 minimumXZ, maximumXZ,
                                 minimumY, maximumY,
                                 minimumXZ, maximumXZ);
                Console.WriteLine();

                // Note: this "look up" is just a very narrow spacial query that (since we know the data)
                // wil only give us one result.
                int    lookUp         = random.Next(0, test);
                string lookUpToString = lookUp.ToString();
                Console.Write("    Look Up (" + lookUp + ", \"" + lookUpToString + "\", " + lookUp + "): ");
                omnitree.Stepper(i => Console.Write(i),
                                 lookUp, lookUp,
                                 lookUp.ToString(), lookUp.ToString(),
                                 lookUp, lookUp);
                Console.WriteLine();

                // Ignoring dimensions on traversals example.
                // If you want to ignore a column on a traversal, you can do so like this:
                omnitree.Stepper(i => { /*Do Nothing*/ },
                                 lookUp, lookUp,
                                 Omnitree.Bound <string> .None, Omnitree.Bound <string> .None,
                                 Omnitree.Bound <decimal> .None, Omnitree.Bound <decimal> .None);

                Console.Write("    Counting Items In a Space [" +
                              "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" +
                              "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: ");
                omnitree.CountSubSpace(
                    minimumXZ, maximumXZ,
                    minimumY, maximumY,
                    minimumXZ, maximumXZ);
                Console.WriteLine();

                int    removalMinimum  = random.Next(1, test / 2);
                int    removalMaximum  = random.Next(1, test / 2) + test / 2;
                string removalMinimumY = removalMinimum.ToString();
                string removalMaximumY = removalMaximum.ToString();
                Console.Write("    Remove (" + removalMinimum + "-" + removalMaximum + "): ");
                omnitree.Remove(
                    removalMinimum, removalMaximum,
                    removalMinimumY, removalMaximumY,
                    removalMinimum, removalMaximum);
                omnitree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    Dimensions: " + omnitree.Dimensions);
                Console.WriteLine("    Count: " + omnitree.Count);

                omnitree.Clear(); // Clears the Omnitree

                Console.WriteLine();
            }
            #endregion

            #region OmnitreeBounds
            {
                Console.WriteLine("  OmnitreeBounds--------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    An Omnitree is an ND SPT that allows for");
                Console.WriteLine("    multidimensional sorting. Any time you need to look");
                Console.WriteLine("    items up based on multiple fields/properties, then");
                Console.WriteLine("    you might want to use an Omnitree. If you need to");
                Console.WriteLine("    perform ranged queries on multiple dimensions, then");
                Console.WriteLine("    the Omnitree is the data structure for you.");
                Console.WriteLine();
                Console.WriteLine("    The \"OmnitreePoints\" stores individual points (vectors),");
                Console.WriteLine("    and the \"OmnitreeBounds\" stores bounded objects (spaces).");
                Console.WriteLine();

                IOmnitreeBounds <int, double, string, decimal> omnitree =
                    new OmnitreeBoundsLinked <int, double, string, decimal>(
                        // This is a location delegate. (how to locate the item along each dimension)
                        (int index,
                         out double min1, out double max1,
                         out string min2, out string max2,
                         out decimal min3, out decimal max3) =>
                {
                    string indexToString = index.ToString();

                    min1 = index; max1 = index;
                    min2 = indexToString; max2 = indexToString;
                    min3 = index; max3 = index;
                });

                Console.Write("    Adding (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    omnitree.Add(i);
                }
                Console.WriteLine();

                Console.Write("    Traversal: ");
                omnitree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                int    minimumXZ = random.Next(1, test / 2);
                int    maximumXZ = random.Next(1, test / 2) + test / 2;
                string minimumY  = minimumXZ.ToString();
                string maximumY  = maximumXZ.ToString();
                Console.Write("    Spacial Traversal [" +
                              "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" +
                              "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: ");
                omnitree.StepperOverlapped(i => Console.Write(i),
                                           minimumXZ, maximumXZ,
                                           minimumY, maximumY,
                                           minimumXZ, maximumXZ);
                Console.WriteLine();

                // Note: this "look up" is just a very narrow spacial query that (since we know the data)
                // wil only give us one result.
                int    lookUpXZ = random.Next(0, test);
                string lookUpY  = lookUpXZ.ToString();
                Console.Write("    Look Up (" + lookUpXZ + ", \"" + lookUpY + "\", " + lookUpXZ + "): ");
                omnitree.StepperOverlapped(i => Console.Write(i),
                                           lookUpXZ, lookUpXZ,
                                           lookUpY, lookUpY,
                                           lookUpXZ, lookUpXZ);
                Console.WriteLine();

                // Ignoring dimensions on traversals example.
                // If you want to ignore a dimension on a traversal, you can do so like this:
                omnitree.StepperOverlapped(i => { /*Do Nothing*/ },
                                           lookUpXZ, lookUpXZ,
                                           // The "None" means there is no bound, so all values are valid
                                           Omnitree.Bound <string> .None, Omnitree.Bound <string> .None,
                                           Omnitree.Bound <decimal> .None, Omnitree.Bound <decimal> .None);

                Console.Write("    Counting Items In a Space [" +
                              "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" +
                              "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: " +
                              omnitree.CountSubSpaceOverlapped(
                                  minimumXZ, maximumXZ,
                                  minimumY, maximumY,
                                  minimumXZ, maximumXZ));
                Console.WriteLine();

                int    removalMinimumXZ = random.Next(1, test / 2);
                int    removalMaximumXZ = random.Next(1, test / 2) + test / 2;
                string removalMinimumY  = removalMinimumXZ.ToString();
                string removalMaximumY  = removalMaximumXZ.ToString();
                Console.Write("    Remove (" + removalMinimumXZ + "-" + removalMaximumXZ + "): ");
                omnitree.RemoveOverlapped(
                    removalMinimumXZ, removalMaximumXZ,
                    removalMinimumY, removalMaximumY,
                    removalMinimumXZ, removalMaximumXZ);
                omnitree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    Dimensions: " + omnitree.Dimensions);
                Console.WriteLine("    Count: " + omnitree.Count);

                omnitree.Clear(); // Clears the Omnitree

                Console.WriteLine();
            }
            #endregion

            #region KD Tree
            {
                Console.WriteLine("  KD Tree------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A KD Tree binary tree that stores points sorted along along an");
                Console.WriteLine("    arbitrary number of dimensions. So it performs multidimensional");
                Console.WriteLine("    sorting similar to the Omnitree (Quadtree/Octree) in Towel, but");
                Console.WriteLine("    it uses a completely different algorithm and format.");
                Console.WriteLine();

                Console.WriteLine("    The generic KD Tree in Towel is still in development.");

                Console.WriteLine();
            }
            #endregion

            #region Graph
            {
                Console.WriteLine("  Graph------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A Graph is a data structure of nodes and edges. Nodes are values");
                Console.WriteLine("    and edges are connections between those values. Graphs are often");
                Console.WriteLine("    used to model real world data such as maps, and are often used in");
                Console.WriteLine("    path finding algoritms. See the \"Algorithms\" example for path");
                Console.WriteLine("    finding examples. This is just an example of how to make a graph.");
                Console.WriteLine("    A \"GraphSetOmnitree\" is an implementation where nodes are stored.");
                Console.WriteLine("    in a Set and edges are stored in an Omnitree (aka Quadtree).");
                Console.WriteLine();

                IGraph <int> graphSetOmnitree = new GraphSetOmnitree <int>();

                Console.WriteLine("    Adding Nodes (0-" + (test - 1) + ")...");
                for (int i = 0; i < test; i++)
                {
                    graphSetOmnitree.Add(i);
                }

                int edgesPerNode = 3;
                Console.WriteLine("    Adding Random Edges (0-3 per node)...");
                for (int i = 0; i < test; i++)
                {
                    // lets use a heap to randomize the edges using random priorities
                    IHeap <(int, int)> heap = new HeapArray <(int, int)>((x, y) => Compare.Wrap(x.Item2.CompareTo(y.Item2)));
                    for (int j = 0; j < test; j++)
                    {
                        if (j != i)
                        {
                            heap.Enqueue((j, random.Next()));
                        }
                    }

                    // dequeue some random edges from the heap and add them to the graph
                    int randomEdgeCount = random.Next(edgesPerNode + 1);
                    for (int j = 0; j < randomEdgeCount; j++)
                    {
                        graphSetOmnitree.Add(i, heap.Dequeue().Item1);
                    }
                }

                Console.Write("    Nodes (Traversal): ");
                graphSetOmnitree.Stepper(i => Console.Write(i));
                Console.WriteLine();

                Console.WriteLine("    Edges (Traversal): ");
                graphSetOmnitree.Stepper((from, to) => Console.WriteLine("      " + from + "->" + to));
                Console.WriteLine();

                int a = random.Next(0, test);
                Console.Write("    Neighbors (" + a + "):");
                graphSetOmnitree.Neighbors(a, i => Console.Write(" " + i));
                Console.WriteLine();

                int b = random.Next(0, test / 2);
                int c = random.Next(test / 2, test);
                Console.WriteLine("    Are Adjacent (" + b + ", " + c + "): " + graphSetOmnitree.Adjacent(b, c));
                Console.WriteLine("    Node Count: " + graphSetOmnitree.NodeCount);
                Console.WriteLine("    Edge Count: " + graphSetOmnitree.EdgeCount);

                graphSetOmnitree.Clear(); // Clears the graph

                Console.WriteLine();
            }
            #endregion

            #region Trie
            {
                Console.WriteLine("  Trie------------------------------------------------");
                Console.WriteLine();
                Console.WriteLine("    A Trie is a tree where portions of the data are stored in each node");
                Console.WriteLine("    such that when you traverse the tree to a leaf, you have read the contents");
                Console.WriteLine("    of that leaf along the way. Because of this, a Trie allows for its values");
                Console.WriteLine("    to share data, which is a form of compression. So a Trie may be used to save");
                Console.WriteLine("    memory. A trie may also be a very useful tool in pattern matching, because");
                Console.WriteLine("    it allows for culling based are portions of the data.");
                Console.WriteLine();

                Console.WriteLine("    The generic Trie in Towel is still in development.");

                Console.WriteLine();
            }
            #endregion

            Console.WriteLine("============================================");
            Console.WriteLine("Examples Complete...");
            Console.ReadLine();
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            #region  Struct
            List <Personel> personelListesi = new List <Personel> {
                new Personel("Hale", "Dağlı", true, 5000),
                new Personel("Aka", "Akurima", false, 4000),
                new Personel("john", "Doe", true, 7500)
            };

            personelListesi.ForEach(p => Console.WriteLine(p.ToString()));
            Console.WriteLine();
            personelListesi.ForEach(p => Console.WriteLine(p.BasHarfler()));

            #endregion

            #region Array
            var personelListesiArray = new Personel[] {
                new Personel("Kadir", "Karagöz"),
                new Personel("John", "Doe", true, 8000),
                new Personel("Can", "Temel", true, 9000),
                new Personel("Gül", "Çiçek", false, 7000)
            };

            foreach (var p in personelListesiArray)
            {
                Console.WriteLine(p.ToString());
            }

            Console.ReadKey();
            #endregion

            #region ArrayList
            var personelListesiArrayList = new ArrayList {
                new Personel("Kadir", "Karagöz"),
                new Personel("John", "Doe", true, 8000)
            };
            personelListesiArrayList.Add(new Personel("Gül", "Çiçek", false, 7000));
            personelListesiArrayList.Remove(0);

            foreach (var p in personelListesiArray)
            {
                Console.WriteLine(p.ToString());
            }

            Console.ReadKey();
            #endregion

            #region StacksArray

            LinearStructures.Stacks.StacksArray gorevListesi = new LinearStructures.Stacks.StacksArray(10); // 10 kapasiteli bir yığın oluştur.
            gorevListesi.Add(new Oge("Kitap Oku."));                                                        // Kitap okuma görevi
            gorevListesi.Add(new Oge("Soru Çöz."));
            gorevListesi.Add(new Oge("Kod Yaz."));
            gorevListesi.Add(new Oge("Kod İncele."));

            Oge s = gorevListesi.Remove();                  // son eklenen elemanı kaldır. (Kod İncele.)
            Console.WriteLine($"{s.Tanim} tamamlandı.");

            s = gorevListesi.Remove();                      // son eklenen elemanı kaldır (Kod Yaz.)
            Console.WriteLine($"{s.Tanim} tamamlandı.");


            Console.WriteLine($"{gorevListesi.Top().Tanim} şimdi yapılacak."); // son eklenen elemanı yazdır.

            s = gorevListesi.Remove();                                         // son eklenen elemanı kaldır (Soru Çöz.)
            Console.WriteLine($"{s.Tanim} tamamlandı.");

            Console.WriteLine("Tüm görevler yapıldımı ? {0}", gorevListesi.isEmpty() ? "Evet" : "Hayır");

            s = gorevListesi.Remove();                      // son eklenen elemanı kaldır (Kitap Oku.)
            Console.WriteLine($"{s.Tanim} tamamlandı.");

            Console.WriteLine("Yapılacak bir şey kaldı mı? {0}", gorevListesi.isFull() ? "Evet" : "Hayır");

            Console.ReadKey();
            #endregion

            #region StacksArrayList
            Console.WriteLine("############### Stacks with ArrayList ################");
            StacksArrayList gorevListesi2 = new StacksArrayList();
            gorevListesi2.Push(new Oge("Kitap Oku."));
            gorevListesi2.Push(new Oge("Kod Yaz."));
            gorevListesi2.Push(new Oge("Kod Oku."));
            gorevListesi2.Push(new Oge("Veri Yapılarına Çalış."));

            Oge s2 = gorevListesi2.Pop();
            Console.WriteLine($"{s2.Tanim} tamamlandı.");

            s2 = gorevListesi2.Pop();
            Console.WriteLine($"{s2.Tanim} tamamlandı.");

            Console.WriteLine("Görevler Tamamlandı mı? {0}", gorevListesi2.StackEmpty() ? "Evet" : "Hayır");

            s2 = gorevListesi2.Pop();
            Console.WriteLine($"{s2.Tanim} tamamlandı.");

            gorevListesi2.Clear();

            Console.WriteLine("Tüm Görevler Yapıldı mı? {0}", gorevListesi2.StackEmpty() ? "Evet" : "Hayır");

            Console.ReadKey();

            #endregion

            #region Stack_C#
            Console.WriteLine("############# C#'ta Stack Yapısı ######################");
            Stack <Oge> gorevListesi3 = new Stack <Oge>();
            gorevListesi3.Push(new Oge("Kitap Oku."));
            gorevListesi3.Push(new Oge("Kod Yaz."));
            gorevListesi3.Push(new Oge("Kod Oku."));
            gorevListesi3.Push(new Oge("Veri Yapılarına Çalış."));

            Oge s3 = gorevListesi3.Pop();
            Console.WriteLine($"{s3.Tanim} tamamlandı.");

            s3 = gorevListesi3.Pop();
            Console.WriteLine($"{s3.Tanim} Tamamlandı.");

            Console.WriteLine("Görevler Tamamlandı mı? {0}", gorevListesi3.Count == 0 ? "Evet" : "Hayır");

            Console.WriteLine("Şimdi Yapılacak Görev: {0}", gorevListesi3.Peek().Tanim);

            s3 = gorevListesi3.Pop();
            Console.WriteLine($"{s3.Tanim} tamamlandı.");

            gorevListesi3.Clear();

            Console.WriteLine("Tüm Görevler Yapıldı mı? {0}", gorevListesi3.Count == 0 ? "Evet" : "Hayır");

            Console.ReadKey();

            #endregion

            #region Queue
            Console.WriteLine("############# Array ile Queue Kullanımı ######################");
            QueueArray yap = new QueueArray(3);
            yap.Enqueue("A");
            yap.Enqueue("B");
            yap.Enqueue("C");
            yap.Enqueue("D");
            yap.Enqueue("E");
            yap.Enqueue("F");

            yap.Dequeue();
            yap.Dequeue();
            yap.Dequeue();

            yap.Enqueue("X");
            yap.Enqueue("Y");

            yap.Dequeue();

            yap.Enqueue("Z");

            for (int i = 0; i < 5; i++)
            {
                yap.Enqueue(i.ToString());
            }

            for (int i = 0; i < 5; i++)
            {
                yap.Dequeue();
            }

            Console.ReadKey();
            #endregion

            #region QueueArrayList
            Console.WriteLine("############# ArrayList ile Queue Kullanımı ######################");
            QueueArrayList yap2 = new QueueArrayList();
            yap2.Enqueue("A");
            yap2.Enqueue("B");
            yap2.Enqueue("C");
            yap2.Enqueue("D");


            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());

            yap2.Enqueue("X");
            yap2.Enqueue("Y");

            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());
            Console.WriteLine(yap2.DeQueue());

            Console.ReadKey();

            #endregion

            #region Queue_C#
            Console.WriteLine("############# C#'ta Queue Yapısı ######################");

            Queue <int> kuyruk = new Queue <int>();
            kuyruk.Enqueue(1);
            kuyruk.Enqueue(2);
            kuyruk.Enqueue(3);
            kuyruk.Enqueue(4);

            Console.WriteLine(kuyruk.Dequeue());
            Console.WriteLine(kuyruk.Dequeue());
            Console.WriteLine(kuyruk.Dequeue());
            Console.WriteLine(kuyruk.Peek());
            Console.WriteLine(kuyruk.Count);
            Console.WriteLine(kuyruk.GetType());
            #endregion

            #region LinkedList
            Console.WriteLine("############# Linked List ######################\n\n");

            LinkedList.LinkedList linkedList = new LinkedList.LinkedList();

            linkedList.listeBasinaElemanEkle(new Eleman(25));
            linkedList.listeyeEkle(new Eleman(55));
            linkedList.listeyeEkle(new Eleman(28));


            Console.WriteLine("Liste Başı: " + linkedList.bas.icerik);
            Console.WriteLine("Liste Başı İleri : " + linkedList.bas.ileri.icerik);

            linkedList.listeBasinaElemanEkle(new LinearStructures.LinkedList.Eleman(36));             // ! [[36,25], [25,55], [55,28], [28,null]]

            Console.WriteLine("Liste Başı: " + linkedList.bas.icerik);
            Console.WriteLine("Liste Başı İleri : " + linkedList.bas.ileri.icerik);

            Eleman arananEleman = linkedList.listedeAra(55);
            if (arananEleman != null)
            {
                Console.WriteLine($"Bulundu : {arananEleman.icerik}");
            }
            else
            {
                Console.WriteLine("Bulunamadı!");
            }

            Eleman ilk = linkedList.ElemanGetir(0);
            Eleman uc  = linkedList.ElemanGetir(3);
            Console.WriteLine("İlk eleman : " + ilk.icerik);
            Console.WriteLine("Üçüncü eleman : " + uc.icerik);

            Console.WriteLine("Liste Başı : " + linkedList.bas.icerik);
            Console.WriteLine("Liste Sonu : " + linkedList.son.icerik);
            Console.WriteLine("Liste başına gelen eleman : " + linkedList.ListeBasindanSil().icerik);
            Console.WriteLine("Liste sonuna gelen eleman : " + linkedList.ListeSonundanSil().icerik);

            linkedList.listeBasinaElemanEkle(new LinearStructures.LinkedList.Eleman(34));           // ! 2
            linkedList.listeBasinaElemanEkle(new LinearStructures.LinkedList.Eleman(74));           // ! 1
            linkedList.listeBasinaElemanEkle(new LinearStructures.LinkedList.Eleman(35));           // ! 0
            Console.WriteLine("1. Elemanın yerine gelen :" + linkedList.ListedenSil(linkedList.ElemanGetir(1)).icerik);
            Console.WriteLine("Listedeki eleman sayısı : " + linkedList.Count());
            Console.ReadLine();


            #endregion

            #region Trees

            #endregion ;
        }