RPN Calculator in PHP

I’ve found this nice little blog a couple of days ago called Programming Praxis (it’s in my blogroll as well) which poses a series of programming challenges.

The challenges found there are much more interesting than the other usual ones you can find online. This being the first reason why I’ve decided (as my time permits it) to fool around and have some fun solving them.

And that is why in the lines to follow I will share my PHP solution to the RPC calculator challenge.

Assuming you have read the briefing (I won’t duplicate it here) I’ll continue with my solution.

My first idea for approaching it was by using the PHP tokenizer to pass the string and find the operators. But as soon as I was around to find, there are no representative tokens for arithmetical operators. So instead I used the other more obvious approach… string comparison.

The application starts out by reading line by line what the user provides, split it in the elements it contains, and if it is valid start processing it.

The processing part works by iterating over the elements, finding two numbers before an operator and execute the operation on them. Afterward replace those elements in the list with the result and start again from the top of list.

That was only my first try, which you can see it here. After writing that code, I took a brake and came up with the following refined version of the solution:

0 Responses to “RPN Calculator in PHP”

Comments are currently closed.
blog comments powered by Disqus