Last active
August 29, 2015 13:56
-
-
Save 42thcoder/8856254 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 许多特殊情况都没考虑 | |
# 除数为0 用户输入字母 括号 | |
class Stack | |
def initialize(size) | |
@stack = Array.new(size) | |
@sp = 0 | |
end | |
def push(value) | |
@stack[@sp] = value | |
@sp += 1 | |
end | |
def pop | |
return nil if @sp == 0 | |
@sp -= 1 | |
@stack[@sp] | |
end | |
def size | |
@sp | |
end | |
def to_string | |
"#{@sp} elements: #{@stack[0...@sp]}" | |
end | |
end | |
class Calculator | |
PRIORITY = {"+" => 0, "-" => 0, "*" => 1, "/" => 1} | |
def initialize(input) | |
p PRIORITY['+'] | |
@operands_stack = Stack.new(input.length) | |
@operators_stack = Stack.new(input.length) | |
input.split().each do |chr| | |
case chr | |
when '+', '-', '*', '/' | |
@operators_stack.push chr | |
else | |
@operands_stack.push chr.to_i | |
end | |
end | |
end | |
def operate(operator, fo, so) | |
case operator | |
when '+' | |
fo + so | |
when '-' | |
fo - so | |
when '*' | |
fo * so | |
when '/' | |
fo / so | |
end | |
end | |
def result | |
until @operators_stack.size == 0 | |
p @operands_stack.to_string | |
operator = @operators_stack.pop | |
next_operator = @operators_stack.pop | |
if next_operator.nil? || PRIORITY[operator] >= PRIORITY[next_operator] | |
return nil if @operands_stack.size <= 1 | |
so = @operands_stack.pop | |
fo = @operands_stack.pop | |
@operands_stack.push operate(operator, fo, so) | |
@operators_stack.push next_operator | |
else | |
return nil if @operands_stack.size <= 1 | |
to = @operands_stack.pop | |
so = @operands_stack.pop | |
fo = @operands_stack.pop | |
@operands_stack.push operate(next_operator, fo, so) | |
@operands_stack.push to | |
@operators_stack.push operator | |
end | |
end | |
def to_string | |
@operands_stack.to_string | |
end | |
end | |
end | |
puts 'Give me a string' | |
input = gets | |
cal = Calculator.new(input) | |
cal.result | |
# p cal.to_string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment