Post Fix (aka Reverse Polish Notations) is what I used heavily in my student days with a HP-21 Calculator, and later HP-25. I actually have a preference for using it because of it’s superior performance and simplicity of implementation.
Code Snippet
- public static double PostFix(IEnumerable<string> terms)
- {
- double first, second;
- var work = new Stack<double>();
- foreach (var term in terms)
- {
- switch (term)
- {
- case "+":
- work.Push(work.Pop() + work.Pop());
- break;
- case "*":
- work.Push(work.Pop() * work.Pop());
- break;
- case "-":
- first = work.Pop();
- second = work.Pop();
- work.Push(second - first);
- break;
- case "/":
- first = work.Pop();
- second = work.Pop();
- work.Push(second / first);
- break;
- default: // no error handling
- work.Push(double.Parse(term));
- break;
- }
- }
- return work.Pop();
- }
Unit tests are easy to write:
Code Snippet
- char[] sep = {' ', '\t', '\r', '\n'};
- string[] testcases = {"5 1 2 + 4 * + 3 -","10 2 /"};
- foreach(var testcase in testcases)
- {
- var answer = Questions.PostFix(testcase.Split(sep, StringSplitOptions.RemoveEmptyEntries));
- Console.WriteLine(string.Format("{0}={1}",testcase,answer));
- }
The results are shown below.
For automated testing, just have a second array with the expected answers (or read everything in from XML).
No comments:
Post a Comment