-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkov.lua
More file actions
69 lines (52 loc) · 1.21 KB
/
markov.lua
File metadata and controls
69 lines (52 loc) · 1.21 KB
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
-- help function
function allwords()
local line = io.read() -- current line
local pos = 1 -- current position in the line
return function () -- iterator function
while line do
local w, e = string.match(line, "(%w+[,;.:]?)()", pos)
if w then
pos = e
return w
else
line = io.read()
pos = 1
end
end
return nil
end
end
function prefix(w1, w2)
return w1 .. " " .. w2
end
local statetab = {}
function insert(prefix, value)
local list = statetab[prefix]
if list == nil then
statetab[prefix] = {value}
else
list[#list + 1] = value
end
end
------------
-- build table
local MAXGEN = 200
local NOWORD = "\n"
local w1, w2 = NOWORD, NOWORD
for nextword in allwords() do
insert(prefix(w1, w2), nextword)
w1 = w2; w2 = nextword;
end
insert(prefix(w1, w2), NOWORD)
-- generate text
w1 = NOWORD; w2 = NOWORD
for i = 1, MAXGEN do
local list = statetab[prefix(w1, w2)]
local r = math.random(#list)
local nextword = list[r]
if nextword == NOWORD then
return
end
io.write(nextword, " ")
w1 = w2; w2 = nextword
end