Click here to Skip to main content
15,896,348 members
Articles / Programming Languages / C#

Shunting Yard in C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
12 Mar 2013CPOL 15.8K   270   8  
An implementation of the Shunting yard algorithm.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Toolsbox.ShuntingYard;

namespace ShuntingYardTest
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                ShuntingYardSimpleMath SY = new ShuntingYardSimpleMath();
                String s = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
                Console.WriteLine("input: {0}", s); Console.WriteLine();
                List<String> ss = s.Split(' ').ToList();
                SY.DebugRPNSteps += new ShuntingYardBase<double, string>.DebugRPNDelegate(SY_DebugRPNSteps);
                SY.DebugResSteps += new ShuntingYardBase<double, string>.DebugResDelegate(SY_DebugResSteps);
                Double res = SY.Execute(ss, null);

                bool ok = res == 3.0001220703125;
                Console.WriteLine("input: {0} = {1} {2}", s, res, (ok ? "Ok" : "Error"));
                Console.ReadKey();
            }
            {
            }
        }

        static void SY_DebugRPNSteps(List<object> inter, List<char> opr)
        {
            Console.Write("RPN ");
            foreach (object o in inter)
                Console.Write("{0} ", o.ToString());
            foreach (char o in opr)
                Console.Write("{0} ", o.ToString());
            Console.WriteLine();
        }

        static void SY_DebugResSteps(List<object> res, List<double> var)
        {
            Console.Write("RPN ");
            foreach (object o in res)
                Console.Write("{0} ", o.ToString());
            Console.Write("\n= ");
            foreach (double o in var)
                Console.Write("{0} ", o.ToString());
            Console.WriteLine();
        }
        
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Denmark Denmark
Software developer

Comments and Discussions