This repository has been archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise23.rb
87 lines (66 loc) · 1.8 KB
/
exercise23.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Exercise 23
class Literal
def initialize(val)
@value = val
end
def evaluate
return @value.to_f
end
end
class ExpressionNode
attr_writer :left_operand, :right_operand
def initialize(op)
@operator = op
end
def evaluate
left = @left_operand.evaluate
right = @right_operand.evaluate
case @operator
when :plus
r = left + right
when :minus
r = left - right
when :times
r = left * right
when :divide
r = left / right
end
return r.to_f
end
end
left = ExpressionNode.new(:divide)
left.left_operand = Literal.new(15)
left.right_operand = Literal.new(3)
right = ExpressionNode.new(:divide)
right.left_operand = Literal.new(24)
right.right_operand = Literal.new(6)
main = ExpressionNode.new(:plus)
main.left_operand = left
main.right_operand = right
raise "Error" if main.evaluate != (15 / 3) + (24 / 6) # TEST 1
left = ExpressionNode.new(:times)
left.left_operand = Literal.new(8)
left.right_operand = Literal.new(12)
right = ExpressionNode.new(:times)
right.left_operand = Literal.new(14)
right.right_operand = Literal.new(32)
main = ExpressionNode.new(:minus)
main.left_operand = left
main.right_operand = right
raise "Error" if main.evaluate != 8 * 12 - 14 * 32 # TEST 2
one = ExpressionNode.new(:divide)
one.left_operand = Literal.new(1)
one.right_operand = Literal.new(2)
two = ExpressionNode.new(:divide)
two.left_operand = Literal.new(1)
two.right_operand = Literal.new(4)
three = ExpressionNode.new(:divide)
three.left_operand = Literal.new(1)
three.right_operand = Literal.new(20)
leftSide = ExpressionNode.new(:plus)
leftSide.left_operand = one
leftSide.right_operand = two
main = ExpressionNode.new(:plus)
main.left_operand = leftSide
main.right_operand = three
raise "Error" if main.evaluate != 1.0/2 + 1.0/4 + 1.0/20 # TEST 3