Skip to content

Instantly share code, notes, and snippets.

@officialhopsof
Created April 15, 2021 17:06
Show Gist options
  • Select an option

  • Save officialhopsof/85f669fc868169dedb0a30a0ac6a7dac to your computer and use it in GitHub Desktop.

Select an option

Save officialhopsof/85f669fc868169dedb0a30a0ac6a7dac to your computer and use it in GitHub Desktop.
Token based calculator
Inst = Struct.new(:op, :a, :b) do
def comp
raise "Missing Operand: a" unless a
raise "Missing Operand: b" unless b
return a.to_i + b.to_i if op == '+'
return a.to_i - b.to_i if op == '-'
raise "Invalid Op: #{op}"
end
end
i1 = "((1+(4+5+2)-3))+(6+8)"
# temp:
# c:
# inst: (23)
# stack: ()
def calc(input)
stack = []
inst = Inst.new
input.each_char do |c|
if c == '('
stack.push(inst)
inst = Inst.new
elsif c == ')'
temp = inst.a
inst = stack.pop
inst.b = temp if inst.a
inst.a = temp unless inst.a
if inst.b
inst = Inst.new(nil, inst.comp, nil)
end
elsif c == '+'
inst.op = '+'
elsif c == '-'
inst.op = '-'
else # c is digit
inst.b = c if inst.a
inst.a = c unless inst.a
if inst.b
inst = Inst.new(nil, inst.comp, nil)
end
end
end
return inst.a
end
puts(calc(i1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment