-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonkey.ex
135 lines (86 loc) · 2.09 KB
/
monkey.ex
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
include std/sequence.e
include std/text.e
/*
uh - variable definition
eeh, aah, ugh - variable names
ooh - print
*/
sequence vars = {}
-----------------------------------------------
main()
-----------------------------------------------
procedure main()
integer tests = 3
line()
-- Print integer literal
processInput("ooh ah ah ah ah ah ah")
line()
-- Define and print 1 variable
processInput("uh eeh ah ; ooh eeh")
line()
-- Define and print 2 variables
processInput("uh eeh ah ; uh aah ah ah ; ooh aah ; ooh eeh")
line()
-- Sum 3 variables
processInput("uh eeh ah ah ah ah ; uh aah ah ah ah ; uh ugh ah ; ooh aah eeh ugh")
line()
showVariables()
end procedure
procedure processInput(sequence input)
sequence lines = split(input,";")
for i=1 to length(lines) do
processLine(trim(lines[i]))
end for
end procedure
procedure processLine(sequence line)
sequence words = split(line)
sequence w = words[1]
if equal(w,"uh") then
sequence id = words[2]
sequence result = getDefValue(id)
words = slice(words,3,length(words))
integer val = getValue(words)
if result[1] = 0 then
-- New variable
vars = append(vars,{id,val})
else
-- Update value
vars[result[1]][2] = val
end if
elsif equal(w,"ooh") then
words = tail(words)
integer num = getValue(words)
printf(1,"%d\n",num)
end if
end procedure
function getValue(sequence words)
integer num = 0
for i=1 to length(words) do
sequence w = words[i]
if equal(w,"ah") then
num += 1
elsif equal(w,"u") then
continue
else
sequence result = getDefValue(w)
num += result[2]
end if
end for
return num
end function
function getDefValue(sequence word)
for i=1 to length(vars) do
if equal(vars[i][1],word) then
return {i,vars[i][2]}
end if
end for
return {0,0}
end function
procedure line()
puts(1,"----------------------\n")
end procedure
procedure showVariables()
for i=1 to length(vars) do
printf(1,"%s = %d\n",{vars[i][1],vars[i][2]})
end for
end procedure