예제 #1
0
파일: Answer2.cs 프로젝트: v4karuna/xjvb3r
        public void StackTest()
        {
            var stack = new LinkedListStack <int>();

            //insert 1 to 10 into stack
            for (int i = 1; i <= 10; i++)
            {
                stack.Push(i);
            }

            //size should be 10
            Assert.Equal(10, stack.Size());

            //pop items and assert to ensure FIFO
            for (int i = 10; i > 0; i--)
            {
                var value = stack.Pop();
                Assert.Equal(i, value);
            }

            //size should be 0
            Assert.Equal(0, stack.Size());

            //poping on empty stack should throw an exception
            Assert.Throws <InvalidOperationException>(() => stack.Pop());
        }
예제 #2
0
        private LinkedListStack <Node> SelectNodes(RelayMessage message)
        {
            LinkedListStack <Node> nodes;
            List <Node>            zoneNodes = _nodesByZone[Me.Zone];

            if (zoneNodes != null)
            {
                // select all other nodes in the current zone if they exist
                nodes = new LinkedListStack <Node>(zoneNodes);
            }
            else
            {
                nodes = new LinkedListStack <Node>();
            }

            if (message.SourceZone == Me.Zone)
            {
                // Add 1 node from each foreign zone
                for (ushort zone = 0; zone < _nodesByZone.Length; zone++)
                {
                    if (zone != Me.Zone)
                    {
                        Node ZoneNode = GetChosenZoneNode(zone);
                        if (ZoneNode != null)
                        {
                            nodes.Push(ZoneNode);
                        }
                    }
                }
            }

            return(nodes);
        }
        public void LinkedListStackTest()
        {
            var stack = new LinkedListStack <int>();

            stack.Push(1);
            stack.Push(2);

            Assert.IsTrue(stack.ItemCount == 2);
            Assert.IsTrue(stack.IsEmpty() == false);
            Assert.IsTrue(stack.Peek() == 2);
            Assert.IsTrue(stack.Pop() == 2);
            Assert.IsTrue(stack.ItemCount == 1);
            stack.Pop();
            Assert.IsTrue(stack.IsEmpty());

            for (int i = 0; i < 1000; i++)
            {
                stack.Push(i);
            }

            Assert.IsTrue(stack.ItemCount == 1000);

            for (int i = 0; i < 1000; i++)
            {
                stack.Pop();
            }

            Assert.IsTrue(stack.ItemCount == 0);
        }
예제 #4
0
        private static string DescribeDestinations(LinkedListStack <Node> destinations)
        {
            if (destinations == null || destinations.Count == 0)
            {
                return("nowhere");
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("to ");
            sb.Append(destinations.Count);
            sb.Append(" nodes:");
            Node[] nodes = destinations.PeekAll();

            foreach (Node node in nodes)
            {
                sb.Append(Environment.NewLine);
                sb.Append("     *");
                sb.Append(node.NodeGroup.GroupName);
                sb.Append(" ");
                sb.Append(node.Host);
                sb.Append(":");
                sb.Append(node.Port);
            }
            return(sb.ToString());
        }
예제 #5
0
 private void GeneratePopulatedExample()
 {
     PopulatedLinkedListStack = new LinkedListStack <string>();
     foreach (var item in Items)
     {
         PopulatedLinkedListStack.Push(item);
     }
 }
        public void Count_PushOneItem_ReturnsOne()
        {
            var stack = new LinkedListStack <int>();

            stack.Push(1);
            Assert.AreEqual(1, stack.Count);
            Assert.IsFalse(stack.IsEmpty);
        }
예제 #7
0
        public void LinkedListStackWorksInLifoOrder()
        {
            var sut = new LinkedListStack <int>();

            sut.Push(1);
            sut.Push(2);
            Assert.Equal(2, sut.Pop());
        }
        public void Peek_PushTwoItemsAndPop_ReturnsHeadElement()
        {
            var stack = new LinkedListStack <int>();

            stack.Push(1);
            stack.Push(2);
            stack.Pop();
            Assert.AreEqual(1, stack.Peek());
        }
예제 #9
0
        public void LinkedListStackIsEnptyWhenAllElementsAreRemoved()
        {
            var sut = new LinkedListStack <int>();

            sut.Push(1);
            sut.Push(2);
            Assert.Equal(2, sut.Pop());
            Assert.Equal(1, sut.Pop());
            Assert.True(sut.IsEmpty);
        }
예제 #10
0
        public void LinkedListStackIncreasesCapacityOnDemand()
        {
            var sut = new LinkedListStack <int>();

            sut.Push(1);
            sut.Push(2);
            Assert.Equal(2, sut.Pop());
            Assert.Equal(1, sut.Pop());
            Assert.True(sut.IsEmpty);
        }
예제 #11
0
        public void LinkedListStackPushTest()
        {
            var linkedListStackStack = new LinkedListStack <int>();

            for (var i = 0; i < Elements; i++)
            {
                linkedListStackStack.Push(i * 10);
            }
            Assert.AreEqual(1000000000, linkedListStackStack.Peek());
        }
예제 #12
0
        public override void Init()
        {
            _arrayStack           = new ArrayStack <int>(100);
            _linkedListStackStack = new LinkedListStack <int>();

            for (var i = 0; i < Elements; i++)
            {
                _arrayStack.Push(i * 10);
                _linkedListStackStack.Push(i * 10);
            }

            base.Init();
        }
예제 #13
0
        public void TestLinkedListStack()
        {
            var stack = new LinkedListStack <int>();

            for (var i = 0; i < 5; i++)
            {
                stack.Push(i);
                Console.WriteLine(stack);
            }

            stack.Pop();
            Console.WriteLine(stack);
        }
예제 #14
0
        [Test] // 1.3.12
        public void CopyStack()
        {
            var input = new LinkedListStack <string>();

            input.Push("three");
            input.Push("two");
            input.Push("one");
            Assert.AreEqual(new string[] { "one", "two", "three" }, input.ToArray());

            var output = CopyStack(input);

            Assert.AreEqual(output.ToArray(), input.ToArray());
        }
예제 #15
0
        internal LinkedListStack <Node> GetNodesForMessage(RelayMessage message)
        {
            if (!Activated)
            {
                return(new LinkedListStack <Node>());
            }

            NodeCluster            cluster;
            LinkedListStack <Node> nodes;

            //messages that, from out of system, go to each cluster
            if (message.IsClusterBroadcastMessage)
            {
                if (MyCluster == null)                 //out of system, each cluster
                {
                    nodes = new LinkedListStack <Node>();
                    for (int clusterIndex = 0; clusterIndex < Clusters.Count; clusterIndex++)
                    {
                        nodes.Push(Clusters[clusterIndex].GetNodesForMessage(message));
                    }
                }
                else                 //in system, my cluster
                {
                    nodes = MyCluster.GetNodesForMessage(message);
                }
            }
            else
            {
                //messages that route to one modded cluster
                //to modded cluster in group
                cluster = GetClusterForId(message.Id, message.IsInterClusterMsg);
                if (cluster != null)
                {
                    if (message.IsInterClusterMsg && cluster.MeInThisCluster)
                    {
                        nodes = new LinkedListStack <Node>();
                        nodes.Push(cluster.Me);
                    }
                    else
                    {
                        nodes = cluster.GetNodesForMessage(message);
                    }
                }
                else
                {
                    nodes = new LinkedListStack <Node>();
                }
            }
            return(nodes);
        }
예제 #16
0
        public static void LinkedListStack()
        {
            LinkedListStack <int> linkedListStack = new LinkedListStack <int>();

            linkedListStack.Push(10);
            linkedListStack.Push(9);
            linkedListStack.Push(8);
            linkedListStack.Push(7);
            linkedListStack.Push(6);
            linkedListStack.Push(5);
            linkedListStack.PrintAll();
            linkedListStack.Pop();
            linkedListStack.Pop();
            linkedListStack.PrintAll();
            Console.Read();
        }
예제 #17
0
        public void LinkedLinkStack()
        {
            var stack = new LinkedListStack <string>();

            stack.Push("turtles");
            stack.Push("all");
            stack.Push("the");
            stack.Push("way");
            stack.Push("down");

            Assert.AreEqual("down", stack.Pop());
            Assert.AreEqual("way", stack.Pop());
            Assert.AreEqual("the", stack.Pop());
            Assert.AreEqual("all", stack.Pop());
            Assert.AreEqual("turtles", stack.Pop());
        }
예제 #18
0
        private Stack <string> CopyStack(Stack <string> source)
        {
            var reverse = new LinkedListStack <string>();
            var output  = new LinkedListStack <string>();

            foreach (var item in source)
            {
                reverse.Push(item);
            }

            foreach (var item in reverse)
            {
                output.Push(item);
            }
            return(output);
        }
예제 #19
0
        /// <summary>
        /// Begins asynchronous processing of a single <see cref="T:MySpace.DataRelay.RelayMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="T:MySpace.DataRelay.RelayMessage"/>.</param>
        /// <param name="state">Callers can put any state they like here.</param>
        /// <param name="callback">The method to call upon completion.</param>
        /// <returns>
        /// Returns an <see cref="T:System.IAsyncResult"/>.
        /// </returns>
        public virtual IAsyncResult BeginHandleMessage(RelayMessage message, object state, AsyncCallback callback)
        {
            if (!message.IsTwoWayMessage)
            {
                // cheat for now and just handle in messages synchronously
                // as long as the type doesn't use sync in messages then
                // we won't block on IO anyway.
                HandleMessage(message);
                return(SynchronousAsyncResult.CreateAndComplete(callback, state));
            }

            LinkedListStack <Node> nodes = PrepareMessage(message);

            Node node;

            if (nodes.Pop(out node))
            {
                var result = new AsynchronousResult <Node>((ar, n, m) =>
                {
                    try
                    {
                        n.EndHandleOutMessage(ar);
                        RetryHandleMessageOnError(message, node);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex);
                    }
                }, node, message);

                var origCallback = callback;
                if (callback != null)
                {
                    callback = ar =>
                    {
                        result.InnerResult = ar;
                        origCallback(result);
                    };
                }
                result.InnerResult = node.BeginHandleOutMessage(message, callback, state);
                return(result);
            }

            message.SetError(RelayErrorType.NoNodesAvailable);

            return(SynchronousAsyncResult.CreateAndComplete(callback, state));
        }
예제 #20
0
            private void Dispose()
            {
                ClearThreads();

                _parallelThreads           = _parallelThreads.DisposeExchange();
                _executionPathQueueBuilder = _executionPathQueueBuilder.DisposeExchange();
                _currentThread.Dispose(this);
                _currentThread    = Thread.Empty;
                _executionMethods = null;
                _partialRun       = false;

                Context.ProcessField = DummyProcess;
                Context = null;

                _processResources = null;
                _automata.ReleaseProcess(this);
            }
예제 #21
0
            public void Push(T val)
            {
                ++Count;
                LinkedListStack <T> stack;

                if (_stacks.Count == 0 || _stacks[_stacks.Count - 1].Count == Threshold)
                {
                    stack = new LinkedListStack <T>();
                    _stacks.Add(stack);
                }
                else
                {
                    stack = _stacks[_stacks.Count - 1];
                }

                stack.Push(val);
            }
예제 #22
0
파일: Stack.cs 프로젝트: FOSS-UCSC/FOSSALGO
    public static void Main(string[] args)
    {
        var llStack = new LinkedListStack();

        llStack.Print();
        llStack.Pop();
        llStack.Push(30);
        llStack.Push(20);
        llStack.Print();
        llStack.Push(50);
        llStack.Push(120);
        llStack.Print();
        llStack.Pop();
        llStack.Pop();
        llStack.Print();
        llStack.Search(20);
    }
        public void LinkedListStack()
        {
            Random random = new Random();
            LinkedListStack <string> Stacklist = new LinkedListStack <string>();

            for (int i = 0; i < CountItems; i++)
            {
                Stacklist.Push($"{i.ToString()}");
            }

            for (int i = 0; i < CountItems; i++)
            {
                if (random.Next(i - RndMax, i + RndMin) == i)
                {
                    Stacklist.Pop();
                }
            }
        }
예제 #24
0
        private static LinkedListStack <Node> PrepareMessage(RelayMessage message)
        {
            LinkedListStack <Node> nodes = NodeManager.Instance.GetNodesForMessage(message);

            message.RelayTTL--;
            SetHydrationPolicy(message);

            if (nodes.Count > 0)
            {
                System.Net.IPAddress myAddress = NodeManager.Instance.MyIpAddress;
                if (myAddress != null)
                {
                    message.AddAddressToHistory(myAddress);
                }
            }

            DebugWriter.WriteDebugInfo(message, nodes);
            return(nodes);
        }
예제 #25
0
        public decimal EvaluatePostfix(string input)
        {
            LinkedListStack <decimal> stack = new LinkedListStack <decimal>();

            foreach (var i in input)
            {
                if (IsOperator(i))
                {
                    decimal result;
                    var     right = decimal.Parse(stack.Pop().ToString());
                    var     left  = decimal.Parse(stack.Pop().ToString());
                    switch (i)
                    {
                    case '+':
                        result = left + right;
                        break;

                    case '-':
                        result = left - right;
                        break;

                    case '*':
                        result = left * right;
                        break;

                    case '/':
                        result = left / right;
                        break;

                    default:
                        result = 0;
                        break;
                    }
                    stack.Push(result);
                }
                else
                {
                    stack.Push(decimal.Parse(i.ToString()));
                }
            }
            return(stack.First());
        }
예제 #26
0
        internal void Add(RelayMessage message, LinkedListStack <Node> nodes)
        {
            TypeSetting typeSetting = NodeManager.Instance.Config.TypeSettings.TypeSettingCollection[message.TypeId];

            Node node;

            while (nodes.Pop(out node))
            {
                bool typesettingThrowOnSyncFailure = false;
                bool typesettingSyncInMessages     = false;
                if (null != typeSetting && !node.NodeCluster.MeInThisCluster)
                {
                    typesettingSyncInMessages     = typeSetting.SyncInMessages;
                    typesettingThrowOnSyncFailure = typeSetting.ThrowOnSyncFailure;
                }

                // Contains no longer works now that the NodeWithMessages structure has
                // been added, loop through and check the settings
                bool bAdded = false;
                foreach (NodeWithMessages nwm in this)
                {
                    NodeWithInfo nwi = GetKeyForItem(nwm);
                    if ((nwi.Node == node) &&
                        (nwi.SyncInMessages == typesettingSyncInMessages) &&
                        (nwi.SkipErrorQueueForSync == typesettingThrowOnSyncFailure))
                    {
                        bAdded = true;
                        this[nwi].Messages.Add(message);
                        break;
                    }
                }
                if (!bAdded)
                {
                    NodeWithInfo     newNWI  = new NodeWithInfo(node, typesettingSyncInMessages, typesettingThrowOnSyncFailure);
                    NodeWithMessages newNode = new NodeWithMessages(newNWI);
                    Add(newNode);
                    this[newNWI].Messages.Add(message);
                }
            }
        }
예제 #27
0
            internal void Initialize(IInstructionReader instructionReader, AutomataContext context)
            {
                if (ReferenceEquals(context.ProcessField, DummyProcess) == false)
                {
                    throw new InvalidOperationException("Context is busy");
                }

                _processResources          = ProcessResources.ThreadLocalInstance.Value;
                _executionPathQueueBuilder = _processResources.ExecutionPathGroupBuilderPool.Get().AddReference();
                _parallelThreads           = _processResources.ThreadListPool.Get().AddReference();
                _executionMethods          = _automata.GetExecutionMethods(context);

                Context = context;
                Context.ProcessField = this;

                var entryPoint = context.EntryPoint;

                if (!(entryPoint is FiniteState state))
                {
                    return;
                }

                var instructionQueue = _processResources.InstructionQueuePool.Get().Mount(instructionReader, _automata);

                _entryPointSubGraph = _automata.EnsureSubGraph(state);

                var initNode = _entryPointSubGraph.InitNode;

                if (initNode.Safe == false)
                {
                    initNode.MakeSafe();
                }

                _currentThread = new Thread(initNode, instructionQueue, context.CreateContextStateInternal())
                {
                    Stack                = _processResources.StackPool.Get().AddReference(),
                    ExecutionQueue       = _processResources.ExecutionPathPool.Get().AddReference(),
                    PredicateResultQueue = _processResources.PredicateResultPool.Get().AddReference()
                };
            }
예제 #28
0
파일: Program.cs 프로젝트: viaches/leetcode
        static void Main(string[] args)
        {
            var arrayStack = new ArrayStack <string>();

            arrayStack.Push("first");
            arrayStack.Push("second");
            arrayStack.Push("third");
            arrayStack.Push("forth");
            arrayStack.Pop();
            arrayStack.Pop();
            arrayStack.Pop();

            var linkedListStack = new LinkedListStack <string>();

            linkedListStack.Push("first");
            linkedListStack.Push("second");
            linkedListStack.Push("third");
            linkedListStack.Push("forth");
            linkedListStack.Pop();
            linkedListStack.Pop();
            linkedListStack.Pop();
        }
예제 #29
0
        private string ShuntingYard(string input)
        {
            LinkedListStack <char> operators = new LinkedListStack <char>();
            Queue <char>           output    = new LinkedListQueue <char>();

            foreach (var i in input)
            {
                if (Char.IsNumber(i))
                {
                    output.Enqueue(i);
                }
                if (IsOperator(i))
                {
                    while (!operators.IsEmpty() && OperatorPrecedence(operators.Peek()) >= OperatorPrecedence(i))
                    {
                        output.Enqueue(operators.Pop());
                    }
                    operators.Push(i);
                }
                if (i == '(')
                {
                    operators.Push(i);
                }
                if (i == ')')
                {
                    while (operators.Peek() != '(')
                    {
                        output.Enqueue(operators.Pop());
                    }
                    operators.Pop();
                }
            }
            while (!operators.IsEmpty())
            {
                output.Enqueue(operators.Pop());
            }

            return(new string(output.ToArray()));
        }
예제 #30
0
        static void Main(string[] args)
        {
            LinkedList      list  = new LinkedList();
            LinkedListStack stack = new LinkedListStack();
            LinkedListQueue queue = new LinkedListQueue();

            list.Add(56);
            list.Add(70);
            list.Add(90);
            list.Add(12);
            list.Add(30);
            list.Add(60);
            list.AddInReverseOrder(22);
            list.AddInReverseOrder(44);
            list.InsertAtParticularPosition(2, 12);
            list.Display();
            list.Total();
            list.DeleteFirst();
            list.DeleteLast();
            list.SearchValueInList(90);
            stack.Push(10);
            stack.Push(20);
            stack.Push(30);
            stack.Push(40);
            stack.Push(50);
            stack.Display();
            stack.Peek();
            stack.Pop();
            stack.IsEmpty();
            queue.Enqueue(12);
            queue.Enqueue(24);
            queue.Enqueue(36);
            queue.Enqueue(48);
            queue.Dequeue();
            queue.Display();
            Console.ReadKey();
        }
        public void SortByDroid()
        {
            LinkedListStack<AstromechDroid> astromechList = new LinkedListStack<AstromechDroid>();
            LinkedListStack<JanitorDroid> janitorList = new LinkedListStack<JanitorDroid>();
            LinkedListStack<ProtocolDroid> protocolList = new LinkedListStack<ProtocolDroid>();
            LinkedListStack<UtilityDroid> utilityList = new LinkedListStack<UtilityDroid>();

            LinkedListQueue<IDroid> tempList = new LinkedListQueue<IDroid>();

            foreach(Droid d in droidCollection)
            {
                if(d is AstromechDroid)
                {
                    astromechList.Add((AstromechDroid)d);
                }
                else if(d is JanitorDroid)
                {
                    janitorList.Add((JanitorDroid)d);
                }
                else if(d is ProtocolDroid)
                {
                    protocolList.Add((ProtocolDroid)d);
                }
                else if(d is UtilityDroid)
                {
                    utilityList.Add((UtilityDroid)d);
                }
            }

            while(astromechList.lastNode.Tail != null)
            {
                tempList.Enqueue(astromechList.PopOff());
            }
            tempList.Enqueue(astromechList.PopOff());

            while(janitorList.lastNode.Tail != null)
            {
                tempList.Enqueue(janitorList.PopOff());
            }
            tempList.Enqueue(janitorList.PopOff());

            while(protocolList.lastNode.Tail != null)
            {
                tempList.Enqueue(protocolList.PopOff());
            }
            tempList.Enqueue(protocolList.PopOff());

            while(utilityList.lastNode.Tail != null)
            {
                tempList.Enqueue(utilityList.PopOff());
            }
            tempList.Enqueue(utilityList.PopOff());

            droidCollection = new IDroid[lengthOfCollection];
            int counter = 0;
            while(counter < lengthOfCollection)
            {
                if(tempList.lastNode != null)
                {
                    droidCollection[counter] = tempList.Dequeue();
                    counter++;
                }
            }
        }