Search code examples
c#algorithmrpn

Reverse polish notation C# don't work correctly


I write an rpn, with a struktogram.

Newest Problem: It is'nt work correctly now.

If input string is "5 + ((1 + 2) * 4) - 3"

My output is: 5 1 2 + 4 * 3 - +

I have to got this result: 5 1 2 + 4 * + 3 -

Edited the source

*That was the original problem, but helped me, and now the original mistakes fixed: *,

At the debug when the loop or int i = 12, the c value is 0\0 or something else and this value is added to output (name: formula) string as a '(' bracket. And I don't know why. And the last '-' operation symbol, don't added to (or not look) at the end of output string (formula) I misgave this problem cause by the '('. I tried the program with other string input value, but always put an '(' to my string, and I don't know why... I saw that It was independt about the numbers of bracket. Always only one '(' add to my string...*) Yes, in english LengyelFormula = rpn (it is hungarian)*

static void Main(string[] args)
    {
        String str = "5 + ( ( 1 + 2 ) *  4 ) −3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input) // this is the rpn method
    {
       Stack stack = new Stack();
       String str = input.Replace(" ",string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++)
       {
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (IsOperandus(x)) // is it operand
           {
               formula.Append(x);
           }
           else if (IsOperator(x))  // is it operation
           {
               if (stack.Count>0 && (char)stack.Peek()!='(' && Prior(x)<=Prior((char)stack.Peek()) )
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               if (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) < Prior((char)stack.Peek()))
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               stack.Push(x);
           }
           else
           {
              char y=(char)stack.Pop();
              if (y!='(')
              {
                  formula.Append(y);
              }
           }
       }
       while (stack.Count>0)
       {
           char c = (char)stack.Pop();
           formula.Append(c);
       }
       return formula.ToString();
    }

    static bool IsOperator(char c)
    {
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c)
    {
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c)
    {
        switch (c)
        {
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz paraméter");                                          
        }
    }
}

Solution

  • using System;
    using System.Collections.Generic;
    using System.Text;
    
    class Sample {
        static void Main(string[] args){
            String str = "5 + ( ( 1 + 2 ) *  4 ) -3";
            String result=LengyelFormaKonvertalas(str);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    
        static String LengyelFormaKonvertalas(String input){
           Stack<char> stack = new Stack<char>();
           String str = input.Replace(" ", string.Empty);
           StringBuilder formula = new StringBuilder();
           for (int i = 0; i < str.Length; i++){
               char x=str[i];
               if (x == '(')
                   stack.Push(x);
               else if (x == ')'){
                   while(stack.Count>0 && stack.Peek() != '(')
                       formula.Append(stack.Pop());
                   stack.Pop();
               } else if (IsOperandus(x)){
                   formula.Append(x);
               } else if (IsOperator(x)) {
                   while(stack.Count>0 && stack.Peek() != '(' && Prior(x)<=Prior(stack.Peek()) )
                       formula.Append(stack.Pop());
                   stack.Push(x);
               }
               else {
                  char y= stack.Pop();
                  if (y!='(') 
                      formula.Append(y);
               }
           }
           while (stack.Count>0) {
               formula.Append(stack.Pop());
           }
           return formula.ToString();
        }
    
        static bool IsOperator(char c){
            return (c=='-'|| c=='+' || c=='*' || c=='/');
        }
        static bool IsOperandus(char c){
            return (c>='0' && c<='9' || c=='.');
        }
        static int Prior(char c){
            switch (c){
                case '=':
                    return 1;
                case '+':
                    return 2;
                case '-':
                    return 2;
                case '*':
                    return 3;
                case '/':
                    return 3;
                case '^':
                    return 4;
                default:
                    throw new ArgumentException("Rossz parameter");                                          
            }
        }
    }