-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path482_interp.rb
68 lines (63 loc) · 1.37 KB
/
482_interp.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'minruby'
def evaluate(tree)
case tree[0]
when "lit"
tree[1]
when "+"
left = evaluate(tree[1])
right = evaluate(tree[2])
left + right
when "-"
left = evaluate(tree[1])
right = evaluate(tree[2])
left - right
when "*"
left = evaluate(tree[1])
right = evaluate(tree[2])
left * right
when "/"
left = evaluate(tree[1])
right = evaluate(tree[2])
left / right
when "%"
left = evaluate(tree[1])
right = evaluate(tree[2])
left % right
when "**"
left = evaluate(tree[1])
right = evaluate(tree[2])
left ** right
when "<"
left = evaluate(tree[1])
right = evaluate(tree[2])
left < right
when "<="
left = evaluate(tree[1])
right = evaluate(tree[2])
left <= right
when "=="
left = evaluate(tree[1])
right = evaluate(tree[2])
left == right
when ">="
left = evaluate(tree[1])
right = evaluate(tree[2])
left >= right
when ">"
left = evaluate(tree[1])
right = evaluate(tree[2])
left > right
else # "!="
left = evaluate(tree[1])
right = evaluate(tree[2])
left != right
end
end
# 1. 計算式の文字列を読み込む
str = gets
# 2. 計算式の文字列を計算の木に変換する
tree = minruby_parse(str)
# 3. 計算の木を実行(計算)する
answer = evaluate(tree)
# 4. 計算結果を出力する
p(answer)