1. Regex - Rubular is a fantastic tool to use when evaluating regex statements. This is part of what I had to use in order to solve the polish notation calculator exercise.
2. Bug Testing - I learned some very important lessons about bug testing today. If you insert puts or p under what you are trying to test you can put out multiple arrays on the command line in order to see what is actually happening and how your values are changing at different phases throughout the method itself.
3. delete_at - This method gives you the ability to delete specific values from an array. This is useful because I had to first calculate values in the array and then after the new value was created I had to find a way to delete the other values to keep the stack in the correct order.
4. match method - this saved the day by matching regex with the strings that were being shoveled into the stack and then once they were matched it triggered specific values in the array to be operated on.
Without further ado, I give you The Polish Notation Calculator. This one was by far the most difficult out of the exercises, but was definitely rewarding to finish. The parts that really got me was figuring out the stack array, regex to identify operators, converting to_i, and deleting the values after they had been operated on in the stack already. Here it is and I'm going to bed...
class RPNCalculator def evaluate(str) array = str.split.to_a stack = [] array.each do |x| if x.match(/\*/) stack << stack.last * stack[stack.length - 2] stack.delete_at(stack.length - 2) stack.delete_at(stack.length - 2) elsif x.match(/\+/) stack << stack.last + stack[stack.length - 2] stack.delete_at(stack.length - 2) stack.delete_at(stack.length - 2) elsif x.match(/\-$/) stack << stack[stack.length - 2] - stack.last stack.delete_at(stack.length - 2) stack.delete_at(stack.length - 2) else stack << x.to_i end end return stack.first end end
No comments:
Post a Comment