18 Eylül 2013 Çarşamba

c#ta infix notasyonu prefixe çevirmek

Prefix ve postfix hesap makinalarında,derleyicilerde kullanılan 4 işlem tekniklerinden birisidir .Bizim bildiğimiz matematiksel denklemleri, fonksiyonları parantez kullanmadan yazmamızı sağlayan bir tekniktir. Polish notation olarak da geçer .Alttaki linkler genel fikri verecektir http://itviewson.files.wordpress.com/2012/06/infixprefixpostfix.pdf
http://www.cs.man.ac.uk/~pjj/cs2121/fix.html
    class Notations
    {
        string fnk;
        char[] oparray = { '+', '-', '/', '*', '^' };
        public Notations(string infix)
        {
            this.fnk = infix;
        }
        bool operandmi(char cr)
        {
            int i = 0;
            while (i<5)
            {
                if (cr == oparray[i])
                    return true;
            }
            return false;
        }
        public string prefix()
        {
            string asd = fnk;
           
            Stack OpStack = new Stack();
            Stack PrefixStack = new Stack();
            int i = asd.Length-1;
            while (i>=0)
            {
                char cr = asd[i];
                if (cr > 47 && cr < 58)
                {
                    PrefixStack.Push(cr);
                    PrefixStack.Push(',');
                    i--;
                }
                else
                {
                    int j = 0;
                    while ( j<5 && cr!=oparray[j] )
                    {
                        j++;
                    }
                    if (j != 5)
                    {
                        OpStack.Push(cr);
                        i--;
                    }
                    else
                    {
                        if (cr == ')')
                        {
                            OpStack.Push(')');
                            i--;
                        }
                        else
                        {
                            if (cr == '(')
                            {
                                char cr2;
                                do
                                {
                                   cr2=OpStack.Pop();
                                   if (cr2 != ')')
                                       PrefixStack.Push(cr2);
                                } while (cr2==')');
                                OpStack.Pop();
                                i--;
                            }
                        }
                    }
                }
            }
            while (OpStack.Count!=0)
            {
                PrefixStack.Push(OpStack.Pop());   
            }
            StringBuilder bl = new StringBuilder();
            while (PrefixStack.Count!=0)
            {
                bl.Append(PrefixStack.Pop());
            }

            return bl.ToString();
        }
    }


Hiç yorum yok:

Yorum Gönder