Created
April 15, 2021 17:06
-
-
Save officialhopsof/85f669fc868169dedb0a30a0ac6a7dac to your computer and use it in GitHub Desktop.
Token based calculator
This file contains hidden or 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
| 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