forked from rayning0/ctci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic_expression_spec.rb
101 lines (92 loc) · 2.69 KB
/
logic_expression_spec.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
def eval(exp)
stack = []
num, op = '', ''
exp.each_char do |char|
# next if [' ', ','].include?(char)
if ['[', '&', '|', '!', '0', '1'].include?(char)
stack << char
elsif char == ']'
if stack[-2] == '['
break
elsif stack[-2] == '!'
num = stack.pop
stack.pop
stack.pop
stack << simple_eval('!', num)
else
num2 = stack.pop
num1 = stack.pop
op = stack.pop
stack.pop
return 'Error: First value is not logic operator' if op == '['
stack << simple_eval(op, num1, num2)
end
end
end
stack.pop
end
def to_bool(num)
num.to_i == 1 ? true : false
end
def to_string(bool)
bool ? '1' : '0'
end
def simple_eval(op, num1, num2 = nil)
case op
when '&'
to_string(to_bool(num1) && to_bool(num2))
when '|'
to_string(to_bool(num1) || to_bool(num2))
when '!'
to_string(!to_bool(num1))
else
'Error: First value is not logic operator'
end
end
describe '#eval' do
it 'evaluates expression with no nesting' do
expect(eval('[&, 1, 0]')).to eq '0'
expect(eval('[&, 0, 0]')).to eq '0'
expect(eval('[&, 1, 1]')).to eq '1'
expect(eval('[!, 1]')).to eq '0'
expect(eval('[!, 0]')).to eq '1'
expect(eval('[|, 1, 0]')).to eq '1'
expect(eval('[|, 1, 1]')).to eq '1'
expect(eval('[|, 0, 0]')).to eq '0'
expect(eval('[1, 0]')).to eq 'Error: First value is not logic operator'
end
it 'evaluates 1 level of nesting' do
expect(eval('[&, 1, [!, 0]]')).to eq '1'
expect(eval('[|, [&, 1, [!, 0]], 0]')).to eq '1'
end
it 'evaluates 2 levels of nesting' do
expect(eval('[|, [&, 1, [!, 0]], [!, [|, [|, 1, 0], [!, 1]]]]')).to eq '1'
# OUTPUT:
# ["["]
# ["[", "|"]
# ["[", "|", "["]
# ["[", "|", "[", "&"]
# ["[", "|", "[", "&", "1"]
# ["[", "|", "[", "&", "1", "["]
# ["[", "|", "[", "&", "1", "[", "!"]
# ["[", "|", "[", "&", "1", "[", "!", "0"]
# ["[", "|", "[", "&", "1", "1"]
# ["[", "|", "1"]
# ["[", "|", "1", "["]
# ["[", "|", "1", "[", "!"]
# ["[", "|", "1", "[", "!", "["]
# ["[", "|", "1", "[", "!", "[", "|"]
# ["[", "|", "1", "[", "!", "[", "|", "["]
# ["[", "|", "1", "[", "!", "[", "|", "[", "|"]
# ["[", "|", "1", "[", "!", "[", "|", "[", "|", "1"]
# ["[", "|", "1", "[", "!", "[", "|", "[", "|", "1", "0"]
# ["[", "|", "1", "[", "!", "[", "|", "1"]
# ["[", "|", "1", "[", "!", "[", "|", "1", "["]
# ["[", "|", "1", "[", "!", "[", "|", "1", "[", "!"]
# ["[", "|", "1", "[", "!", "[", "|", "1", "[", "!", "1"]
# ["[", "|", "1", "[", "!", "[", "|", "1", "0"]
# ["[", "|", "1", "[", "!", "1"]
# ["[", "|", "1", "0"]
# ["1"]
end
end