Peek() public method

public Peek ( ) : Object
return Object
Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            // Stack - A LIFO collection

            Stack<string> stack = new Stack<string>();

            stack.Push("A");  // Push adds to the stack
            stack.Push("B");
            stack.Push("C");
            stack.Push("D");

            Console.WriteLine(stack.Peek()); // D - Peek returns the last added value without removing it

            Console.WriteLine(stack.Pop()); // D - Pop returna the last added value and removes it

            Console.WriteLine(stack.Peek());  // C

            // Queue - A FIFO collection

            Queue<string> queue = new Queue<string>();

            queue.Enqueue("a"); // Enqueue adds to the queue
            queue.Enqueue("b");
            queue.Enqueue("c");
            queue.Enqueue("d");

            Console.WriteLine(queue.Peek()); // a - Peek returns the beginning value without removing it

            Console.WriteLine(queue.Dequeue()); // a - Dequeue returns the beginning value and removes it

            Console.WriteLine(queue.Peek()); // b

            //--
            Console.ReadKey();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Stack ast = new Stack();
            ast.Push("Item 1");
            ast.Push("Item 2");
            ast.Push("Item 3");
            ast.Push("Item 4");

            Console.WriteLine("Count:    {0}", ast.Count);
            PrintValues(ast);

            // Peek item but do not remove
            object item = ast.Peek();
            Console.WriteLine("Peek: {0}", item);
            PrintValues(ast);

            // Peek and cast but do not remove
            string itemString = ast.Peek() as string;   // fast cast
            Console.WriteLine("Peek: {0}", item);
            PrintValues(ast);

            // Contains
            Boolean contains = ast.Contains("Item 3");
            Console.WriteLine("Contains: {0}", contains);

            // Remove items
            object item4 = ast.Pop();
            object item3 = ast.Pop();
            Console.WriteLine("Pop: {0}  {1}", item4, item3);
            PrintValues(ast);
            Console.WriteLine("Count:    {0}", ast.Count);

            // no TrimToSize method
        }
Ejemplo n.º 3
0
        private void stackButton_Click(object sender, EventArgs e)
        {
            Stack pilha = new Stack();

            //Adicionando itens
            pilha.Push("banana");
            pilha.Push("laranja");
            pilha.Push("uva");

            //Exibindo os itens da coleção
            foreach (string elemento in pilha)
            {
                listBox1.Items.Add(elemento);
            }
            listBox1.Items.Add("--------------");

            //Exibindo o item do topo da pilha
            listBox1.Items.Add("topo da pilha");
            listBox1.Items.Add(pilha.Peek());
            listBox1.Items.Add("--------------");

            //Retirando um elemento da pilha (do topo)
            pilha.Pop();

            //Exibindo o item do topo da pilha
            listBox1.Items.Add("topo da pilha");
            listBox1.Items.Add(pilha.Peek());

        }
Ejemplo n.º 4
0
 public static bool Intercambiar(ListBox listaA, ListBox listaB, Stack destino, Stack origen)
 {
     Object item = listaB.SelectedItem;
     if (item.ToString() != origen.Peek().ToString())
     {
         MessageBox.Show("El elemnto no se puede mover", "Torres de Hanoi", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         listaB.ClearSelected();
     }
     else{
         if (destino.Count == 0 || ((int)origen.Peek() < (int)destino.Peek()))
         {
             listaA.Items.Insert(0, item);
             listaB.Items.Remove(item);
             destino.Push(origen.Peek());
             origen.Pop();
             return true;
         }
     else
         {
             MessageBox.Show("Movimiento no valido", "Torres de Hanoi", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
             listaB.ClearSelected();
         }
     }
     return false;
 }
Ejemplo n.º 5
0
        public static mysToken Evaluate(
			mysSymbol symbol,
			mysToken value,
			Stack<mysSymbolSpace> spaceStack
		)
        {
            // NOTICE THIS
            // since each function has it's own internal space
            // before grabbing our reference to the space in which
            // we want to define our symbol, we need to pop the
            // internal off, or we're going to be defining the symbol
            // in our internal space, i.e. it will scope out as soon as
            // we're done. So we pop the internal off, grab our reference
            // to the space outside of that, then push the internal back on.
            mysSymbolSpace top = spaceStack.Pop();
            mysSymbolSpace ss = spaceStack.Peek();

            if ( value.Type == typeof(mysFunction) ) {
                defineFunction(
                    symbol,
                    value.Value as mysFunction,
                    spaceStack.Peek()
                );
            } else {
                mysSymbolSpace space = symbol.DefinedIn( spaceStack );
                if ( space != null ) {
                    space.Define( symbol, value );
                } else {
                    ss.Define( symbol, value );
                }
            }

            spaceStack.Push( top );
            return null;
        }
Ejemplo n.º 6
0
        internal void ObjectProcessComponent(int index, LineTypes.Component line, IParentObject obj, Stack<GameObject> objectStack, Stack<ParserContext> contextStack, ParserContext context)
        {
            #region Object context
            if (context == this.objectContext) {
                switch (index) {
                    case 0:
                    case 2:
                        return;
                    case 1:
                        MeshFilter filter = objectStack.Peek().AddComponent<MeshFilter>();
                        MeshRenderer renderer = objectStack.Peek().AddComponent<MeshRenderer>();
                        filter.mesh = Utility.MeshHelper.GetQuad();
                        renderer.material = new Material(Shader.Find("Standard"));
                        return;
                }
            }
            #endregion

            if (context == this.objectContext.Components[2].context) {
                // COLLIDER

                // todo: this
            }

            // other components that have sub-components

            throw new Exception("Invalid member in parsed lines list");
        }
        /**
         * Leetcode online judge: int[] as input argument
         * 208ms
         */
        public static int largestRectangleArea2(int[] height)
        {
            Stack S = new Stack();
            int len = height.Length;
            int[] newH = new int[len + 1];

            for (int i = 0; i < len; i++)
                newH[i] = height[i];

            newH[len] = 0;

            int sum = 0;
            for (int i = 0; i < newH.Length; i++)
            {
                if (S.Count == 0 || (int)newH[i] > (int)newH[(int)S.Peek()])
                    S.Push(i);
                else
                {
                    int tmp = (int)S.Peek();
                    S.Pop();

                    int value_i = (int)newH[tmp];
                    sum = Math.Max(sum, value_i * ((S.Count == 0) ? i : i - (int)S.Peek() - 1));
                    i--;
                }
            }

            return sum;
        }
 public int LongestValidParentheses(string s)
 {
     Stack<int> stack = new Stack<int>();
     char[] arr = s.ToCharArray();
     int result = 0;
     for (int i = 0; i < arr.Length; i++)
     {
         if (arr[i] == '(')
         {
             stack.Push(i);
         }
         else
         {
             if (stack.Count != 0 && arr[stack.Peek()] == '(')
             {
                 stack.Pop();
                 result = Math.Max((stack.Count == 0 ? i + 1 : i - stack.Peek()), result);
             }
             else
             {
                 stack.Push(i);
             }
         }
     }
     return result;
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            // Declare stack collection
            Stack myStack = new Stack();

            // Push elements onto the stack
            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Pop off an element
            myStack.Pop(); // gets top value

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Clear stack
            myStack.Clear();

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
Ejemplo n.º 10
0
 public static LexemV8 Parse(string data)
 {
     if (String.IsNullOrEmpty(data))
     {
         return null;
     }
     Stack<LexemV8> _lexemStack = new Stack<LexemV8>();
     LexemV8 lexemV8 = null;
     for (int i = 0; i < data.Length; i++)
     {
         char ch = data[i];
         if (ch == StartLexem
             && IsValidStringLexem(lexemV8))
         {
             LexemV8 braceLexemV8 = new LexemV8 { LexemType = LexemV8Type.Brace };
             if (_lexemStack.Count > 0)
             {
                 LexemV8 parentBrace = _lexemStack.Peek();
                 parentBrace.AddChild(braceLexemV8);
             }
             _lexemStack.Push(braceLexemV8);
         }
         else if (ch == DelimiterLexem
             && IsValidStringLexem(lexemV8))
         {
             LexemV8 parentBrace = _lexemStack.Peek();
             parentBrace.AddChild(lexemV8);
             lexemV8 = null;
         }
         else if(ch == EndLexem
             && IsValidStringLexem(lexemV8))
         {
             LexemV8 parentBrace = _lexemStack.Pop();
             parentBrace.AddChild(lexemV8);
             if (_lexemStack.Count == 0)
             {
                 lexemV8 = parentBrace;
             }
             else
             {
                 lexemV8 = null;
             }
         }
         else if (NeedAddChar(lexemV8, ch))
         {
             if (lexemV8 == null)
             {
                 lexemV8 = new LexemV8();
             }
             lexemV8.AddChar(ch);
         }
     }
     return lexemV8;
 }
Ejemplo n.º 11
0
        override public void EnterRule(string filename, string ruleName)
        {
            if (backtracking > 0)
            {
                return;
            }
            ParseTree parentRuleNode = (ParseTree)callStack.Peek();
            ParseTree ruleNode       = Create(ruleName);

            parentRuleNode.AddChild(ruleNode);
            callStack.Push(ruleNode);
        }
Ejemplo n.º 12
0
 public string[] ConvertToPostfixNotation(string input)
 {
     List<string> outputSeparated = new List<string>();
     Stack<string> stack = new Stack<string>();
     foreach (string c in Separate(input))
     {
         if (operators.Contains(c))
         {
             if (stack.Count > 0 && !c.Equals("("))
             {
                 if (c.Equals(")"))
                 {
                     string s = stack.Pop();
                     while (s != "(")
                     {
                         outputSeparated.Add(s);
                         s = stack.Pop();
                     }
                 }
                 else if (GetPriority(c) > GetPriority(stack.Peek()))
                 {
                     stack.Push(c);
                 }
                 else
                 {
                     while (stack.Count > 0 && GetPriority(c) <= GetPriority(stack.Peek()))
                     {
                         outputSeparated.Add(stack.Pop());
                     }
                     stack.Push(c);
                 }
             }
             else
             {
                 stack.Push(c);
             }
         }
         else
         {
             outputSeparated.Add(c);
         }
     }
     if (stack.Count > 0)
     {
         foreach (string c in stack)
         {
             outputSeparated.Add(c);
         }
     }
     return outputSeparated.ToArray();
 }
Ejemplo n.º 13
0
        private void button2_Click(object sender, EventArgs e)
        {
            //ʵ����
            Stack myStack = new Stack();
            //ʹ��Push������ջ
            myStack.Push("A");
            myStack.Push("B");
            myStack.Push("C");
            myStack.Push("C");

            //����ջԪ��
            Console.WriteLine("\nmyStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }

            //ʹ��Pop������ջ
            Console.WriteLine("\nItem pulled from myStack: " + myStack.Pop().ToString());
            Console.WriteLine("\nAfter myStack.Pop(),myStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }

            //Peek����ֻ����ջ��Ԫ�أ�����ջ��ɾ��
            Console.WriteLine("\nmyStack.Peek() : " + myStack.Peek().ToString());
            Console.WriteLine("\nAfter myStack.Peek(),myStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }
        }
Ejemplo n.º 14
0
Archivo: Game.cs Proyecto: Lyloox/Abimn
        protected override void Draw(GameTime gameTime)
        {
            if (G.currentGame.Count == 0)
                return;

            Stack<GameType> buffer = new Stack<GameType>();

            GraphicsDevice.Clear(Color.Black);

            while (G.currentGame.Count != 1 && !G.currentGame.Peek().IsFullScreen)
                buffer.Push(G.currentGame.Pop());
            buffer.Push(G.currentGame.Pop());
            G.spriteBatch.Begin();
            while (buffer.Count != 0)
            {
                buffer.Peek().Draw();
                G.currentGame.Push(buffer.Pop());
            }
            Cursor.Draw();

            black.Draw();
            white.Draw();

            G.spriteBatch.End();

            base.Draw(gameTime);
        }
Ejemplo n.º 15
0
        public int Dequeue()
        {
            var x = (int)s1.Peek();

            s1.Pop();
            return(x);
        }
Ejemplo n.º 16
0
        //Main_7_9_6
        public static void Main_7_9_6()
        {
            Queue myQueue = new Queue();
            //��Queueβ�����Ԫ��
            myQueue.Enqueue("��");
            myQueue.Enqueue("��");
            myQueue.Enqueue("˭");

            //����Queueu��ʼ��Ԫ��
            Console.WriteLine(myQueue.Peek());
            //���ز��Ƴ�Queue��ʼ��Ԫ��
            myQueue.Dequeue();

            //����Queue
            foreach (object o in myQueue)
                Console.WriteLine(o.ToString());

            Stack myStack = new Stack();
            //��Stack��������Ԫ��
            myStack.Push("��");
            myStack.Push("��");
            myStack.Push("˭");

            //����Stack������Ԫ��
            Console.WriteLine(myStack.Peek());
            //���ز��Ƴ�Stack������Ԫ��
            myStack.Pop();

            //����Stack
            foreach (object o in myStack)
                Console.WriteLine(o.ToString());
        }
Ejemplo n.º 17
0
 public void PushHistory()
 {
     //if (!IsPostBack)
     {
         URLHISTORY_NODE          node      = new URLHISTORY_NODE();
         System.Collections.Stack stSession = (System.Collections.Stack)Session["URLHistoryStack"];
         node.szKey = Request.FilePath.ToLower();
         node.szURL = Request.Url.ToString();
         if (stSession != null)
         {
             if (stSession.Count > 0)
             {
                 URLHISTORY_NODE topnode = (URLHISTORY_NODE)stSession.Peek();
                 if (topnode.szKey != node.szKey)
                 {
                     stSession.Push(node);
                 }
             }
             else
             {
                 stSession.Push(node);
             }
         }
         else
         {
             System.Collections.Stack stNow = new System.Collections.Stack();
             stNow.Push(node);
             Session["URLHistoryStack"] = stNow;
         }
     }
 }
Ejemplo n.º 18
0
		/// <summary>
		/// Returns a line composed of the words in the stack that would
		/// fit into the label.	
		/// The line is returned when the next word wouldn't fit or the last poped
		/// word was a newline.
		/// 
		/// The stack is requiered to have all characters and all whitespaces in
		/// separate elements. The labels text must be blank.
		/// </summary>
		public static string getLine( Stack<string> words, UILabel targetLabel, bool doLinePadding ){
			string line = "";
			string currWord = "";
			Vector2 labelSize = new Vector2( targetLabel.width, targetLabel.height );
			Vector2 textSize  = new Vector2();
			targetLabel.UpdateNGUIText();
			
			//Add next word to the current line as long as the line would fit in the label
			//and not cause a newline.
			while( words.Count > 0 ){
				currWord = words.Peek();
				textSize = NGUIText.CalculatePrintedSize(line + currWord);
				
				if( textSize.y > labelSize.y ){	
					//Check if the current word is a whitespace. If it is, remove it
					if( currWord.Trim() == string.Empty ){
						words.Pop();
						line.Trim();
					}
					textSize = NGUIText.CalculatePrintedSize(line + " ");
					while( textSize.y < labelSize.y && doLinePadding ){
						line += " ";
						textSize = NGUIText.CalculatePrintedSize(line + " ");
					}
					return line;
				}
				line += words.Pop();
			}
			
			return line;
		}			
Ejemplo n.º 19
0
 static void Main(string[] args)
 {
     string valor;
     Stack mipila = new Stack();
     //ingreso de elementos a la pila
     mipila.Push("z");
     mipila.Push("ba");
     mipila.Push("nom");
     //imprimir elementos de la pila pueden ser de tipo char, int, string o
     //cualquier otro tipo ya que es un tipo object dependera de lo que el
     //usuario necesite
     foreach (string var in mipila)
     {
         Console.WriteLine(var);
     }
     Console.WriteLine("\n\n");
     //Peek RETORNA el valor que esta al tope de la pila sin eliminarlo
     Console.WriteLine("El tope de la pila es");
     Console.WriteLine(mipila.Peek());
     //retorna el valor del tope eliminandolo
     valor = mipila.Pop().ToString();
     Console.WriteLine("eliminado de la pila: " + valor);
     Console.WriteLine("\n\n");
     //mostrando contenido de la pila
     foreach (string var in mipila)
     {
         Console.WriteLine(var);
     }
     Console.ReadLine();
 }
        /// <summary>
        /// Converts infix formula notation to postfix notation
        /// </summary>
        /// <param name="mathString">String representation of mathematical formula 
        /// (Allowed operations are +, -, *, /, ^)</param>
        /// <returns>String array of tokens in postfix notation</returns>
        public static string[] InfixToPostfix(string mathString)
        {
            Stack<String[]> stackOperands = new Stack<string[]>();
            Stack<Operator> stackOperators = new Stack<Operator>();

            string[] tokenArray = LexicalParse(mathString);

            foreach (string token in tokenArray)
            {
                if (Operators.ContainsKey(token))
                {
                    Operator operatorTemp = Operators[token];
                    if (stackOperators.Count != 0 &&
                        operatorTemp.Priority <= stackOperators.Peek().Priority)
                    {
                        do
                        {
                            AtomicInfixToPostfix(stackOperands, stackOperators);
                        }
                        while (
                            stackOperators.Count != 0 &&
                            operatorTemp.Priority <= stackOperators.Peek().Priority);

                        stackOperators.Push(operatorTemp);

                    }
                    else if (
                        (stackOperators.Count != 0 &&
                        operatorTemp.Priority > stackOperators.Peek().Priority) ||
                        stackOperators.Count == 0)
                    {
                        stackOperators.Push(operatorTemp);
                    }
                }
                else
                {
                    stackOperands.Push(new string[] { token });
                }
            }
            do
            {
                AtomicInfixToPostfix(stackOperands, stackOperators);
            }
            while (stackOperators.Count != 0);

            return stackOperands.Peek();
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            int T = int.Parse(Console.ReadLine());
            for (int i = 0; i < T; i++)
            {
                char[] line = Console.ReadLine().ToCharArray();
                Stack<char> ops = new Stack<char>();
                char opFound;
                StringBuilder postFix = new StringBuilder();
                for (int j = 0; j < line.Length; j++)
                {
                    char c =line[j];

                    if (c != '(' && c != ')' && c != '*' && c != '+' && c != '/' && c != '-' && c != '^')
                    {
                        postFix.Append(c);
                    }
                    else if(c=='(')
                    {
                        ops.Push(c);
                    }
                    else if(c==')')
                    {
                        opFound = ops.Pop();
                        while (opFound != '(')
                        {
                            postFix.Append(opFound);
                            opFound = ops.Pop();
                        }
                    }
                    else
                    {
                        if((ops.Count!=0)&& Predecessor(ops.Peek(),c)){
                            opFound = ops.Pop();
                            while(Predecessor(opFound,c)){
                                postFix.Append(opFound);
                                if (ops.Count == 0)
                                    break;
                                opFound = ops.Pop();
                            }
                            ops.Push(c);
                        }
                        else
                        {
                            ops.Push(c);
                        }
                    }

                }
                while (ops.Count > 0)
                {
                    opFound = ops.Pop();
                    postFix.Append(opFound);
                }
                Console.WriteLine(postFix.ToString());

            }
            Console.ReadLine();
        }
        public override IEnumerator GetEnumerator()
        {
            isRunning = true;

            int startingCount = registeredEnumerators.Count;

            while (registeredEnumerators.Count > 0)
            {
                //create a new stack for each task
                Stack<IEnumerator> stack = new Stack<IEnumerator>();
                //let`s get the first available task
                IEnumerator task = registeredEnumerators.Dequeue();
                //put in the stack
                stack.Push(task);

                while (stack.Count > 0)
                {
                    IEnumerator ce = stack.Peek(); //get the current task to execute

                    if (ce is AsyncTask)
                        (ce as AsyncTask).token = _token;

                    if (ce.MoveNext() == false)
                    {
                        _progress = (float)(startingCount - registeredEnumerators.Count) / (float)startingCount;
                        _subProgress = 0;

                        stack.Pop(); //task is done (the iteration is over)
                    }
                    else
                    {
                        if (ce.Current != ce && ce.Current != null)  //the task returned a new IEnumerator (or IEnumerable)
                        {
                            if (ce.Current is WWW || ce.Current is YieldInstruction)
                                yield return ce.Current; //YieldInstructions are special cases and must be handled by Unity. They cannot be wrapped!
                            else
                            if (ce.Current is IEnumerable)
                                stack.Push(((IEnumerable)ce.Current).GetEnumerator()); //it's pushed because it can yield another IEnumerator on its own
                            else
                            if (ce.Current is IEnumerator)
                                stack.Push(ce.Current as IEnumerator); //it's pushed because it can yield another IEnumerator on its own
                        }

                        if (ce is AsyncTask) //asyn
                            _subProgress = (ce as AsyncTask).task.progress * (((float)(startingCount - (registeredEnumerators.Count)) / (float)startingCount) - progress);

                        if (ce is EnumeratorWithProgress) //asyn
                            _subProgress = (ce as EnumeratorWithProgress).progress * (((float)(startingCount - (registeredEnumerators.Count)) / (float)startingCount) - progress);
                    }

                    yield return null; //the tasks are not done yet
                }
            }

            isRunning = false;

            if (onComplete != null)
                onComplete();
        }
Ejemplo n.º 23
0
        public override IEnumerator GetEnumerator()
        {
            isRunning = true;

            listOfStacks.Clear();

            foreach (IEnumerator enumerator in registeredEnumerators)
            {
                Stack<IEnumerator> stack = new Stack<IEnumerator>();

                stack.Push(enumerator);

                listOfStacks.Add(stack);
            }

            registeredEnumerators.Clear();

            Debug.Log("Parallel Tasks Started, number of tasks: " + listOfStacks.Count);

            while (listOfStacks.Count > 0)
            {
                for (int i = 0; i < listOfStacks.Count; ++i)
                {
                    Stack<IEnumerator> stack = listOfStacks[i];

                    if (stack.Count > 0)
                    {
                        IEnumerator ce = stack.Peek(); //without popping it.

                        if (ce.MoveNext() == false)
                            stack.Pop(); //now it can be popped
                        else //ok the iteration is not over
                        if (ce.Current != null && ce.Current != ce)
                        {
                            if (ce.Current is IEnumerable)	//what we got from the enumeration is an IEnumerable?
                                stack.Push(((IEnumerable)ce.Current).GetEnumerator());
                            else
                            if (ce.Current is IEnumerator)	//what we got from the enumeration is an IEnumerator?
                                stack.Push(ce.Current as IEnumerator);
                        }

                        yield return null;
                    }
                    else
                    {
                        listOfStacks.RemoveAt(i);
                        i--;
                    }
                }
            }

            Debug.Log("All Parallel Tasks Ended");

            isRunning = false;

            if (onComplete != null)
                onComplete();
        }
        public Expression convertToExpression()
        {
            List<string> mc = new List<string>(convertToPostfixNotation().Split(' '));
            Stack<Expression> stack = new Stack<Expression>();
            List<string> listVar = getVar();

            Debug.WriteLine(mc[0]);

            for (int i = 0; i < mc.Count; i++)
            {
                string tmp = mc[i].ToString();

                if (isConstisVar(tmp))
                    stack.Push(new Number(tmp == "1"));

                if (isVar(tmp))
                    stack.Push(new Variable(listVar.BinarySearch(tmp)));

                if (isMatch(tmp))
                {
                    switch (tmp)
                    {
                        case "↔":
                            stack.Push(new Equivalence(stack.Pop(), stack.Pop()));
                            break;
                        case "↓":
                            stack.Push(new PierceArrow(stack.Pop(), stack.Pop()));
                            break;
                        case "|":
                            stack.Push(new ShefferStroke(stack.Pop(), stack.Pop()));
                            break;
                        case "→":
                            stack.Push(new Implication(stack.Pop(), stack.Pop()));
                            break;
                        case "←":
                            stack.Push(new ConverseImplication(stack.Pop(), stack.Pop()));
                            break;
                        case "ᐯ":
                            stack.Push(new Union(stack.Pop(), stack.Pop()));
                            break;
                        case "⊕":
                            stack.Push(new Modulo2(stack.Pop(), stack.Pop()));
                            break;
                        case "ᐱ":
                            stack.Push(new Intersection(stack.Pop(), stack.Pop()));
                            break;
                        case "¬":
                            stack.Push(new Negation(stack.Pop()));
                            break;
                    }
                }
                Debug.WriteLine(stack.Peek());
            }

            return stack.Pop();
        }
Ejemplo n.º 25
0
        public TreeNode Parse(string s)
        {
            var root = new TreeNode();
            var stack = new Stack<TreeNode>();
            stack.Push(root);
            foreach (var c in s)
            {
                var current = stack.Peek();
                if (current.IsEnd(c))
                {
                    stack.Pop();
                }
                else if (IsStart(c))
                {
                    if (current.GetType() == typeof(TextTreeNode))
                    {
                        stack.Pop();
                        current = stack.Peek();
                    }
                    //create node of that type
                    var boldTreeNode = new BoldTreeNode();
                    current.Add(boldTreeNode);
                    stack.Push(boldTreeNode);
                }
                else
                {
                    if (current.GetType() != typeof(TextTreeNode))
                    {
                        var textNode = new TextTreeNode();
                        textNode.Add(c);
                        current.Add(textNode);
                        stack.Push(textNode);
                    }
                    else
                    {
                        var textNode = (TextTreeNode) current;
                        textNode.Add(c);
                    }
                }
            }

            return root;
        }
            void ITemplateCommand.Apply(Stack<object> values)
            {
                object component = values.Peek();
                if (property.IsReadOnly) {
                    TryAggregation(component);
                    return;
                }

                property.SetValue(component, name, value);
            }
Ejemplo n.º 27
0
 public void CleanupSemantic(ArrayList diffs)
 {
     var    changes      = false;
     var    candidates   = new Stack<int>();  // Stack of indices where equalities are found.
     string lastCandidat = null;  // Always equal to equalities[equalitiesLength-1][1]
     int    lastIndex    = 0;
     int    lastLength   = 0;
     var    pointer      = 0; // Index of current position.
     var length_changes1 = 0; // Number of characters that changed prior to the equality.
     var length_changes2 = 0; // Number of characters that changed after the equality.
     while (pointer < diffs.Count) {
         DiffResultSpan diff = (DiffResultSpan)diffs[pointer];
         if (diff.Status == DiffResultSpanStatus.NoChange) {  // equality found
             candidates.Push(pointer);
             length_changes1 = length_changes2;
             length_changes2 = 0;
             lastCandidat    = GetSrcLineByIndex(diff.SourceIndex);
             lastIndex       = diff.SourceIndex;
             lastLength      = diff.Length;
         } else {  // an insertion or deletion
             length_changes2 += diff.Length;
             if (lastCandidat != null && (lastCandidat.Length <= length_changes1) && (lastCandidat.Length <= length_changes2)) {
                 DiffResultSpan diffeq = (DiffResultSpan)diffs[candidates.Peek()];
                 diffs.Insert(candidates.Peek(), DiffResultSpan.CreateDeleteSource(lastIndex, lastCandidat.Length + diffeq.Length));
                 diffeq.Status = DiffResultSpanStatus.AddDestination;
                 candidates.Pop();
                 if (candidates.Count > 0)
                     candidates.Pop();
                 pointer = candidates.Count > 0 ? candidates.Peek() : -1;
                 length_changes1 = 0;  // Reset the counters.
                 length_changes2 = 0;
                 lastCandidat    = null;
                 changes = true;
             }
         }
         pointer++;
     }
     if (changes) {
         CleanupMerge(diffs);
     }
     CleanupSemanticLossless(diffs);
 }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            Stack myStack = new Stack();

            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            //Have a peek at the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Pop();
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Clear();
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
Ejemplo n.º 29
0
        static int countingNesting(string textForAnalys)
        {
            string [] linesOfCode = textForAnalys.Split('\r') ;
               var stackForCounting = new Stack<string>();
               int maximalNesting = 0;
               int currentNesting = 0;

               for ( int countLines = 0; countLines < linesOfCode.Length; countLines++)
               {
               string [] wordsOfLine = linesOfCode[countLines].Split(new Char [] {' ', '\n', '\r'});
               for (int arrayCount = 0; arrayCount<wordsOfLine.Length; arrayCount++)
               {
                   if (wordsOfLine[arrayCount] == "if" | wordsOfLine[arrayCount] == "for" | wordsOfLine[arrayCount] == "while" | wordsOfLine[arrayCount] == "repeat" | wordsOfLine[arrayCount] == "else")
                   {
                       if (wordsOfLine[arrayCount] == "if") currentNesting++;
                       stackForCounting.Push(wordsOfLine[arrayCount]);
                   }
                   if (stackForCounting.Count != 0)
                   {
                       if (wordsOfLine[arrayCount] == "end;" & (stackForCounting.Peek() == "if"))
                       {
                           stackForCounting.Pop();
                           currentNesting--;
                        }
                       else
                       if (wordsOfLine[arrayCount] == "end;" & (stackForCounting.Peek() != "if"))
                           stackForCounting.Pop();

                       if (wordsOfLine[arrayCount] == "end")
                           for (int stackElements = stackForCounting.Count; stackElements > 1; stackElements--)
                           {
                               if (stackForCounting.Peek() == "if") currentNesting--;
                               stackForCounting.Pop();
                           }
                   }
                   if (currentNesting > maximalNesting)
                       maximalNesting = currentNesting;
               }
               }
               return maximalNesting ;
        }
Ejemplo n.º 30
0
    public override void VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var typeSymbol = semanticModel.GetDeclaredSymbol(node);

        FAMIX.Type type = type = importer.EnsureType(typeSymbol, typeof(FAMIX.Class));
        node.Modifiers.ToList <SyntaxToken>().ForEach(token => type.Modifiers.Add(token.Text));
        var superType = typeSymbol.BaseType;

        if (superType != null)
        {
            FAMIX.Type baseType = null;
            if (superType.DeclaringSyntaxReferences.Length == 0)
            {
                baseType = importer.EnsureBinaryType(superType);
            }
            else
            {
                baseType = importer.EnsureType(typeSymbol.BaseType, typeof(FAMIX.Class));
            }
            Inheritance inheritance = importer.CreateNewAssociation <Inheritance>(typeof(FAMIX.Inheritance).FullName);
            inheritance.subclass   = type;
            inheritance.superclass = baseType;
            baseType.AddSubInheritance(inheritance);
            type.AddSuperInheritance(inheritance);
        }

        //type.name = node.Identifier.ToString();
        AddSuperInterfaces(typeSymbol, type);
        AddAnnotations(typeSymbol, type);
        AddParameterTypes(typeSymbol, type);
        currentTypeStack.Push(type);
        importer.CreateSourceAnchor(type, node);
        type.isStub = false;
        if (type.container != null)
        {
            type.container.isStub = false;
        }
        base.VisitClassDeclaration(node);
        ComputeFanout(currentTypeStack.Peek() as FAMIX.Type);
        currentTypeStack.Pop();
    }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            Stack myStack = new Stack();

            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            // Have a peek at the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Pop(); // pops "item 3" off the top
            // now "item 2" is the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Clear(); // get rid of everything
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
Ejemplo n.º 32
0
 public static Stack<int> Sort(Stack<int> stack)
 {
     var t = new Stack<int>();
     while (stack.Count > 0) {
         int temp = stack.Pop();
         while(t.Count > 0 && t.Peek() < temp){
             stack.Push(t.Pop());
         }
         t.Push(temp);
     }
     return t;
 }
Ejemplo n.º 33
0
        public static int FactorialStack(int n)
        {
            Stack<int> stack = new Stack<int>();
            int ret = 1;
            stack.Push(n);
            while (stack.Peek() > 1) {
                ret *= stack.Pop();
                stack.Push(n -= 1);
            }

            return ret;
        }
Ejemplo n.º 34
0
        public void MostrarPila(ListBox lista, Stack pila, Label turno)
        {
            lista.Items.Clear();
            //Mostrar los valores
            foreach (Persona item in pila)
                lista.Items.Add(item);

            if (pila.Count > 0)
                turno.Text = String.Format("Turno: {0}", pila.Peek());
            else
                turno.Text = "Sin elementos";
        }
Ejemplo n.º 35
0
 static public int Peek(IntPtr l)
 {
     try {
         System.Collections.Stack self = (System.Collections.Stack)checkSelf(l);
         var ret = self.Peek();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 36
0
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                System.Collections.Stack stack =
                    (System.Collections.Stack)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value;

                try
                {
                    object obj = stack.ToArray();

                    stackframe.player.linktypemapper.storeLinkObject_ToSlot(obj,functionDefine.signature.returnType,returnSlot,bin,stackframe.player);
                    //returnSlot.setValue((int)array.GetValue(index));
                    success = true;
                }
                catch (RuntimeLinkTypeMapper.TypeLinkClassException tlc)
                {
                    success = false;
                    stackframe.throwAneException(token,tlc.Message);
                }
                catch (KeyNotFoundException)
                {
                    success = false;
                    stackframe.throwAneException(token,(stack.Peek() != null ? stack.Peek().ToString() : (stack.ToString() + ".peek()的值")) + "没有链接到脚本");
                }
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
                catch (InvalidOperationException io)
                {
                    success = false;
                    stackframe.throwAneException(token,io.Message);
                }
            }
 static int Peek(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Collections.Stack obj = (System.Collections.Stack)ToLua.CheckObject(L, 1, typeof(System.Collections.Stack));
         object o = obj.Peek();
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 38
0
        public static Stack SortStackMethod(Stack input)
        {
            Stack helperStack = new System.Collections.Stack();

            while (input.Count != 0)
            {
                int temp = (int)input.Pop();
                while (helperStack.Count > 0 && (int)helperStack.Peek() > temp)
                {
                    input.Push(helperStack.Pop());
                }

                helperStack.Push(temp);
            }
            return(helperStack);
        }
        public void MethodStack()
        {
            s = new Stack(20);

            s.Push("Element");

            if (!(s.Peek().Equals("Element")))
            {
                Environment.Exit(-1);
            }

            Object[] objs = s.ToArray();

            if (!(objs[0].Equals("Element")))
            {
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 40
0
        public void Main()
        {
            myStack.Push("Ashin");
            myStack.Push(true);
            myStack.Push(null);
            myStack.Push(4);
            myStack.Push(62.2);
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }
            myStack.Pop();
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }

            Console.WriteLine(myStack.Peek());
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }
        }
Ejemplo n.º 41
0
        public void SetAction(Action Action)
        {
            //			if (!Action.WorksOnLayoutView)
            //			{	// das ist jetzt besser gelöst mit "OnlyThisView" etc.
            //				frame.AssureModelView(); // geht nur mit ModelView!
            //			}
            if (Action.ChangeTabInControlCenter)
            {
                Action.returnToTabPage = frame.GetActivePropertyDisplay();
                frame.ShowPropertyDisplay("Action");
            }
            Action.ActionStack = this;
            Action.OnSetAction(); // erstes Ereigniss für die neue Aktion (noch nicht auf dem Stack)
            Frame.RaiseActionStartedEvent(Action);
            Action OldAction = null;

            if (Actions.Count > 0)
            {
                OldAction = Actions.Peek() as Action;
            }
            // folgende Schleife ist notwendig, da bei Inactivate eine Aktion sich
            // selbst entfernen kann. Dann aber bekommt die drunterliegende ein Activate
            // was gleich wieder von einem Inactivate gefolgt werden muss
            while (OldAction != null)
            {
                OldAction.OnInactivate(Action, false); // alte Aktion inaktivieren (kann sich auch verabschieden)
                if (Actions.Count > 0)
                {
                    if (OldAction != Actions.Peek())
                    {
                        OldAction = Actions.Peek() as Action;
                    }
                    else
                    {
                        OldAction = null;
                    }
                }
                else
                {
                    OldAction = null;
                }
            }
            Actions.Push(Action);
            Action.OnActivate(OldAction, true);
        }
Ejemplo n.º 42
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public ParseTreeNode convertInfixNotationToASTForIcePlugin(String paramString) throws Exception
        public virtual ParseTreeNode convertInfixNotationToASTForIcePlugin(string paramString)
        {
            System.Collections.Stack stack1 = new System.Collections.Stack();
            System.Collections.Stack stack2 = new System.Collections.Stack();
            string[] arrayOfString          = paramString.Split("", true);
            sbyte    b1    = 0;
            string   str   = "";
            bool     @bool = true;

            for (sbyte b2 = 0; b2 < arrayOfString.Length; b2++)
            {
                string str2;
                bool   bool1;
                string str1;
                if (arrayOfString[b2].Equals(" ") || arrayOfString[b2].Equals(""))
                {
                    b1 = 1;
                }
                else if (arrayOfString[b2].Equals("("))
                {
                    b1 = 2;
                }
                else if (arrayOfString[b2].Equals(")"))
                {
                    b1 = 3;
                }
                else
                {
                    b1 = 4;
                }
                switch (b1)
                {
                case 1:
                    break;

                case 2:
                    stack1.Push("(");
                    break;

                case 3:
                    while (true)
                    {
                        if (stack1.Count > 0)
                        {
                            string str3 = (string)stack1.Pop();
                            if ("(".Equals(str3))
                            {
                                break;
                            }
                            addNode(stack2, str3);
                            continue;
                        }
                        throw new System.InvalidOperationException("Unbalanced right parentheses");
                    }
                    break;

                default:
                    if (this.operators.ContainsKey(arrayOfString[b2]))
                    {
                        @bool = false;
                        BaseOperator baseOperator1 = (BaseOperator)this.operators[arrayOfString[b2]];
                        BaseOperator baseOperator2;
                        while (stack1.Count > 0 && null != (baseOperator2 = (BaseOperator)this.operators[stack1.Peek()]) && ((!baseOperator1.RightAssociative && 0 == baseOperator1.comparePrecedence(baseOperator2)) || baseOperator1.comparePrecedence(baseOperator2) < 0))
                        {
                            stack1.Pop();
                            addNode(stack2, baseOperator2.Symbol + "");
                        }
                        stack1.Push(arrayOfString[b2]);
                        break;
                    }
                    str1  = arrayOfString[b2];
                    bool1 = b2 + true;
                    while (b2 + true < arrayOfString.Length && !arrayOfString[b2 + true].Equals(" ") && !arrayOfString[b2 + true].Equals("(") && !arrayOfString[b2 + true].Equals(")") && !this.operators.ContainsKey(arrayOfString[b2 + true]))
                    {
                        str1 = str1 + arrayOfString[b2 + true];
                        b2++;
                    }
                    str2 = str1;
                    str1 = createValidNameForInput(str1);
                    if (str1.EndsWith("R", StringComparison.Ordinal) && str1.IndexOf("R", StringComparison.Ordinal) != 0)
                    {
                        string str3 = str1.Substring(0, str1.Length - 1);
                        str1 = "( ROUND( (" + str3 + "- INT(" + str3 + ")) * (10^( LEN(ROUND(" + str3 + " - INT(" + str3 + "),2))-2)),4))";
                    }
                    else if (str1.EndsWith("L", StringComparison.Ordinal) && str1.IndexOf("L", StringComparison.Ordinal) != 0)
                    {
                        str1 = "INT(" + str1.Substring(0, str1.Length - 1) + ")";
                    }
                    else if (str1.EndsWith("\"", StringComparison.Ordinal))
                    {
                        if (str1.Substring(0, str1.Length - 1).EndsWith("R", StringComparison.Ordinal) && str1.IndexOf("R", StringComparison.Ordinal) != 0)
                        {
                            string str3 = str1.Substring(0, str1.Length - 2);
                            str1 = "( ROUND( (" + str3 + "- INT(" + str3 + ")) * (10^( LEN(ROUND(" + str3 + " - INT(" + str3 + "),2))-2)),4))";
                        }
                        else if (str1.Substring(0, str1.Length - 1).EndsWith("L", StringComparison.Ordinal) && str1.IndexOf("L", StringComparison.Ordinal) != 0)
                        {
                            str1 = "INT(" + str1.Substring(0, str1.Length - 1) + "\")";
                        }
                    }
                    stack2.Push(new ParseTreeNode(str1, null, null));
                    break;
                }
            }
            while (stack1.Count > 0)
            {
                addNode(stack2, (string)stack1.Pop());
            }
            return((ParseTreeNode)stack2.Pop());
        }
 /// <summary>
 /// Returns, but does not remove, the top of the stack.
 /// </summary>
 internal Frame Peek()
 {
     return((Frame)(_frames.Peek()));
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Advances the enumerator to the next element in the random access
        /// list.
        /// </summary>
        /// <returns>
        /// <b>true</b> if the enumerator was successfully advanced to the
        /// next element; <b>false</b> if the enumerator has passed the end
        /// of the collection.
        /// </returns>
        public bool MoveNext()
        {
            // Move index to the next position.
            index++;

            // If the index has moved beyond the end of the list, return false.
            if (index >= count)
            {
                return(false);
            }

            RalTreeNode currentNode;

            // Get the node at the top of the stack.
            currentNode = (RalTreeNode)treeStack.Peek();

            // Get the value at the top of the stack.
            current = currentNode.Value;

            // If there are still left children to traverse.
            if (currentNode.LeftChild != null)
            {
                // If the left child is not null, the right child should not be
                // null either.
                Debug.Assert(currentNode.RightChild != null);

                // Push left child onto stack.
                treeStack.Push(currentNode.LeftChild);
            }
            // Else the bottom of the tree has been reached.
            else
            {
                // If the left child is null, the right child should be null,
                // too.
                Debug.Assert(currentNode.RightChild == null);

                // Move back up in the tree to the parent node.
                treeStack.Pop();

                RalTreeNode previousNode;

                // Whild the stack is not empty.
                while (treeStack.Count > 0)
                {
                    // Get the previous node.
                    previousNode = (RalTreeNode)treeStack.Peek();

                    // If the bottom of the left tree has been reached.
                    if (currentNode == previousNode.LeftChild)
                    {
                        // Push the right child onto the stack so that the
                        // right tree will now be traversed.
                        treeStack.Push(previousNode.RightChild);

                        // Finished.
                        break;
                    }
                    // Else the bottom of the right tree has been reached.
                    else
                    {
                        // Keep track of the current node.
                        currentNode = previousNode;

                        // Pop the stack to move back up the tree.
                        treeStack.Pop();
                    }
                }

                // If the stack is empty.
                if (treeStack.Count == 0)
                {
                    // Move to the next tree in the list.
                    currentTopNode = currentTopNode.NextNode;

                    // If the end of the list has not yet been reached.
                    if (currentTopNode != null)
                    {
                        // Begin with the next tree.
                        treeStack.Push(currentTopNode.Root);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 45
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public ParseTreeNode convertInfixNotationToAST(String paramString) throws Exception
        public virtual ParseTreeNode convertInfixNotationToAST(string paramString)
        {
            System.Collections.Stack stack1 = new System.Collections.Stack();
            System.Collections.Stack stack2 = new System.Collections.Stack();
            string[] arrayOfString          = paramString.Split("", true);
            sbyte    b1    = 0;
            string   str   = "";
            bool     @bool = true;

            for (sbyte b2 = 0; b2 < arrayOfString.Length; b2++)
            {
                bool   bool1;
                string str1;
                if (arrayOfString[b2].Equals(" "))
                {
                    b1 = 1;
                }
                else if (arrayOfString[b2].Equals("("))
                {
                    b1 = 2;
                }
                else if (arrayOfString[b2].Equals(")"))
                {
                    b1 = 3;
                }
                else
                {
                    b1 = 4;
                }
                switch (b1)
                {
                case 1:
                    break;

                case 2:
                    stack1.Push("(");
                    break;

                case 3:
                    while (true)
                    {
                        if (stack1.Count > 0)
                        {
                            string str2 = (string)stack1.Pop();
                            if ("(".Equals(str2))
                            {
                                break;
                            }
                            addNode(stack2, str2);
                            continue;
                        }
                        throw new System.InvalidOperationException("Unbalanced right parentheses");
                    }
                    break;

                default:
                    if (this.operators.ContainsKey(arrayOfString[b2]))
                    {
                        @bool = false;
                        BaseOperator baseOperator1 = (BaseOperator)this.operators[arrayOfString[b2]];
                        BaseOperator baseOperator2;
                        while (stack1.Count > 0 && null != (baseOperator2 = (BaseOperator)this.operators[stack1.Peek()]) && ((!baseOperator1.RightAssociative && 0 == baseOperator1.comparePrecedence(baseOperator2)) || baseOperator1.comparePrecedence(baseOperator2) < 0))
                        {
                            stack1.Pop();
                            addNode(stack2, baseOperator2.Symbol + "");
                        }
                        stack1.Push(arrayOfString[b2]);
                        break;
                    }
                    str1  = arrayOfString[b2];
                    bool1 = b2 + true;
                    while (b2 + true < arrayOfString.Length && !arrayOfString[b2 + true].Equals(" ") && !arrayOfString[b2 + true].Equals("(") && !arrayOfString[b2 + true].Equals(")") && !this.operators.ContainsKey(arrayOfString[b2 + true]))
                    {
                        str1 = str1 + arrayOfString[b2 + true];
                        b2++;
                    }
                    stack2.Push(new ParseTreeNode(str1, null, null));
                    break;
                }
            }
            while (stack1.Count > 0)
            {
                addNode(stack2, (string)stack1.Pop());
            }
            return((ParseTreeNode)stack2.Pop());
        }
Ejemplo n.º 46
0
        public bool Read()
        {
            // find the next <element>
            int  intElementSpace   = 0;
            int  intElementNameEnd = 0;
            bool blnElementFound   = false;

            while (!(blnElementFound || mintCurrentPosition >= mstrInput.Length))
            {
                switch (mstrInput.Substring(mintCurrentPosition, 1))
                {
                case "<":                                               // element start (or end)
                    if (mstrInput.Substring(mintCurrentPosition, 2) == "</")
                    {
                        // element end
                        mstrName = mobjStack.Peek().ToString();
                        if (mstrInput.Substring(mintCurrentPosition, mstrName.Length + 3) == "</" + mstrName + ">")
                        {
                            // long-form element close, pop the current stack item
                            mobjStack.Pop();
                        }
                        mintCurrentPosition = mintCurrentPosition + (mstrName.Length + 3);
                    }
                    else
                    {
                        // element start
                        if (mstrInput.Substring(mintCurrentPosition, 2) == "<?")
                        {
                            // xml or other declaration, skip
                            intElementNameEnd   = mstrInput.Substring(mintCurrentPosition).IndexOf(">");
                            mintCurrentPosition = mintCurrentPosition + intElementNameEnd;
                        }
                        else
                        {
                            intElementNameEnd = mstrInput.Substring(mintCurrentPosition).IndexOf(">");
                            intElementSpace   = mstrInput.Substring(mintCurrentPosition).IndexOf(" ");
                            if (intElementSpace > 0 && intElementSpace < intElementNameEnd)
                            {
                                mstrName            = mstrInput.Substring(mintCurrentPosition + 1, intElementSpace - 1);
                                mintCurrentPosition = mintCurrentPosition + intElementSpace + 1;
                            }
                            else
                            {
                                mstrName            = mstrInput.Substring(mintCurrentPosition + 1, intElementNameEnd - 1);
                                mintCurrentPosition = mintCurrentPosition + intElementNameEnd + 1;
                            }
                            mobjStack.Push(mstrName);
                            blnElementFound = true;
                        }
                    }
                    break;

                case "/":                                               // short-form element close
                    if (mstrInput.Substring(mintCurrentPosition, 2) == "/>")
                    {
                        //  pop the current stack item
                        mobjStack.Pop();
                        mstrName            = mobjStack.Peek().ToString();
                        mintCurrentPosition = mintCurrentPosition + 2;
                    }
                    else
                    {
                        mintCurrentPosition = mintCurrentPosition + 1;
                    }
                    break;

                default:
                    mintCurrentPosition = mintCurrentPosition + 1;
                    break;
                }
            }
            return(!(mobjStack.Count == 0) & !(mintCurrentPosition >= mstrInput.Length));
        }
Ejemplo n.º 47
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public java.util.List<String> getOperantsListForIce(String paramString) throws Exception
        public virtual IList <string> getOperantsListForIce(string paramString)
        {
            List <object> arrayList = new List <object>();

            System.Collections.Stack stack1 = new System.Collections.Stack();
            System.Collections.Stack stack2 = new System.Collections.Stack();
            string[] arrayOfString          = paramString.Split("", true);
            sbyte    b1    = 0;
            string   str   = "";
            bool     @bool = true;

            for (sbyte b2 = 0; b2 < arrayOfString.Length; b2++)
            {
                string str3;
                string str2;
                bool   bool1;
                string str1;
                if (arrayOfString[b2].Equals(" ") || StringUtils.isNullOrBlank(arrayOfString[b2]))
                {
                    b1 = 1;
                }
                else if (arrayOfString[b2].Equals("("))
                {
                    b1 = 2;
                }
                else if (arrayOfString[b2].Equals(")"))
                {
                    b1 = 3;
                }
                else
                {
                    b1 = 4;
                }
                switch (b1)
                {
                case 1:
                    break;

                case 2:
                    stack1.Push("(");
                    break;

                case 3:
                    while (true)
                    {
                        if (stack1.Count > 0)
                        {
                            string str4 = (string)stack1.Pop();
                            if ("(".Equals(str4))
                            {
                                break;
                            }
                            addNode(stack2, str4);
                            continue;
                        }
                        throw new System.InvalidOperationException("Unbalanced right parentheses");
                    }
                    break;

                default:
                    if (this.operators.ContainsKey(arrayOfString[b2]))
                    {
                        @bool = false;
                        BaseOperator baseOperator1 = (BaseOperator)this.operators[arrayOfString[b2]];
                        BaseOperator baseOperator2;
                        while (stack1.Count > 0 && null != (baseOperator2 = (BaseOperator)this.operators[stack1.Peek()]) && ((!baseOperator1.RightAssociative && 0 == baseOperator1.comparePrecedence(baseOperator2)) || baseOperator1.comparePrecedence(baseOperator2) < 0))
                        {
                            stack1.Pop();
                            addNode(stack2, baseOperator2.Symbol + "");
                        }
                        stack1.Push(arrayOfString[b2]);
                        break;
                    }
                    str1  = arrayOfString[b2];
                    bool1 = b2 + true;
                    while (b2 + true < arrayOfString.Length && !arrayOfString[b2 + true].Equals(" ") && !arrayOfString[b2 + true].Equals("(") && !arrayOfString[b2 + true].Equals(")") && !this.operators.ContainsKey(arrayOfString[b2 + true]))
                    {
                        str1 = str1 + arrayOfString[b2 + true];
                        b2++;
                    }
                    str2 = null;
                    if (str1.EndsWith("R", StringComparison.Ordinal) && str1.LastIndexOf("R", StringComparison.Ordinal) != 0)
                    {
                        str2 = str1.Substring(0, str1.Length - 1);
                        stack2.Push(new ParseTreeNode(str2, null, null));
                    }
                    else if (str1.EndsWith("L", StringComparison.Ordinal) && str1.LastIndexOf("L", StringComparison.Ordinal) != 0)
                    {
                        str2 = str1.Substring(0, str1.Length - 1);
                        stack2.Push(new ParseTreeNode(str2, null, null));
                    }
                    else if (str1.EndsWith("\"", StringComparison.Ordinal))
                    {
                        if (str1.Substring(0, str1.Length - 1).EndsWith("R", StringComparison.Ordinal) && str1.LastIndexOf("R", StringComparison.Ordinal) != 0)
                        {
                            str2 = str1.Substring(0, str1.Length - 2);
                            stack2.Push(new ParseTreeNode(str2, null, null));
                        }
                        else if (str1.Substring(0, str1.Length - 1).EndsWith("L", StringComparison.Ordinal) && str1.LastIndexOf("L", StringComparison.Ordinal) != 0)
                        {
                            str2 = str1.Substring(0, str1.Length - 1);
                            stack2.Push(new ParseTreeNode(str2, null, null));
                        }
                    }
                    str3 = str1;
                    str1 = createValidNameForInput(str1);
                    if (!string.ReferenceEquals(str2, null) && !isNumeric(str2) && !str2.StartsWith("@", StringComparison.Ordinal))
                    {
                        arrayList.Add(str2);
                        stack2.Push(new ParseTreeNode(str1, null, null));
                        break;
                    }
                    if (!string.ReferenceEquals(str1, null) && !isNumeric(str1) && !str1.StartsWith("@", StringComparison.Ordinal))
                    {
                        arrayList.Add(str1);
                        stack2.Push(new ParseTreeNode(str1, null, null));
                        break;
                    }
                    stack2.Push(new ParseTreeNode(str1, null, null));
                    break;
                }
            }
            while (stack1.Count > 0)
            {
                addNode(stack2, (string)stack1.Pop());
            }
            return(arrayList);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Создает  массив, в котором располагаются операторы и символы представленные в обратной польской записи (безскобочной)
        /// На этом же этапе отлавливаются почти все остальные ошибки (см код). По сути - это компиляция.
        /// </summary>
        /// <returns>массив обратной польской записи</returns>
        public static System.Collections.ArrayList CreateStack()
        {
            //Собственно результирующий массив
            System.Collections.ArrayList strarr = new System.Collections.ArrayList(30);
            //Стек с операторами где они временно храняться
            System.Collections.Stack operators = new System.Collections.Stack(15);
            string expr = expression;

            //пооператорная обработка выражения
            while (expr != "")
            {
                string op = expr.Substring(0, expr.IndexOf(" ")); // берём кусок выражения обрамлённый пробелами
                expr = expr.Substring(expr.IndexOf(" ") + 1);     // отсекаем от выражения взятый кусок
                switch (op)
                {
                case "(":     //1
                {
                    //Кладем в стэк
                    operators.Push(op);
                    break;
                }

                case "m":     //4
                {
                    //вытаскиваем из стека все операторы чей приоритет больше либо равен унарному минусу
                    while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            // переполнгение стека - возвращем null
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "p":     //4
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "m" | operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "*":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "/":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "mod":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "+":     //2
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "+" || operators.Peek().ToString() == "-" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "-":     //2
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" | operators.Peek().ToString() == "/" | operators.Peek().ToString() == "mod" | operators.Peek().ToString() == "+" | operators.Peek().ToString() == "-" | operators.Peek().ToString() == "m" | operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case ")":
                {
                    while (operators.Peek().ToString() != "(")
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Pop();
                    break;
                }

                default:
                {
                    //на входе - число - помещаем в выходной массив
                    if (strarr.Capacity > strarr.Count)
                    {
                        strarr.Add(op);
                    }
                    else
                    {
                        return(null);
                    }
                    break;
                }
                }
            }
            //записываем все что осталовь в стеке в выходной массив
            while (operators.Count != 0)
            {
                strarr.Add(operators.Pop());
            }
            return(strarr);
        }
Ejemplo n.º 49
0
    static void Main()
    {
        System.Collections.Stack OperatorStack = new System.Collections.Stack();
        List <string>            Output        = new List <string>();
        string OutputStr;
        int    loops;
        string Express = "";
        string Letter;

        loops = int.Parse(Console.ReadLine());

        for (int i = 0; i != loops - 1; i++)
        {
            Express = Console.ReadLine();

            foreach (char c in Express)
            {
                Letter = c.ToString();

                switch (Letter)
                {
                case "a":
                case "b":
                case "c":
                case "d":
                case "e":
                case "f":
                case "g":
                case "h":
                case "i":
                case "j":
                case "k":
                case "l":
                case "m":
                case "n":
                case "o":
                case "p":
                case "q":
                case "r":
                case "s":
                case "t":
                case "u":
                case "v":
                case "w":
                case "x":
                case "y":
                case "z":

                    Output.Add(Letter);
                    break;

                case "+":
                case "-":
                case "*":
                case "/":
                case "^":

                    while (OperatorStack.Peek().ToString() == "+" | OperatorStack.Peek().ToString() == "-" | OperatorStack.Peek().ToString() == "+" | OperatorStack.Peek().ToString() == "+")
                    {
                    }


                    OperatorStack.Push(Letter);
                    break;

                case "(":

                    OperatorStack.Push(Letter);
                    break;

                case ")":

                    while (OperatorStack.Peek().ToString() != "(")
                    {
                        Output.Add(OperatorStack.Pop().ToString());
                    }
                    OperatorStack.Pop();
                    break;
                }
            }

            if (OperatorStack.Count != 0)
            {
                while (OperatorStack.Peek() != null)
                {
                    Output.Add(OperatorStack.Pop().ToString());
                }
            }

            OutputStr = string.Join("", Output.ToArray());
            Console.WriteLine(OutputStr);
            Output.Clear();
            OperatorStack.Clear();
        }
    }
Ejemplo n.º 50
0
 public UIManager.State NavigationStackPeek()
 {
     return((UIManager.State)navigationStack.Peek());
 }
Ejemplo n.º 51
0
 public static object peek(System.Collections.Stack st)
 {
     return(st.Peek());
 }