-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllg.lua
More file actions
executable file
·73 lines (62 loc) · 1.6 KB
/
llg.lua
File metadata and controls
executable file
·73 lines (62 loc) · 1.6 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
65
66
67
68
69
70
71
72
73
#!/usr/bin/env lua
local function trim(s)
return s:match'^%s*(.*%S)' or ''
end
local function makeGraph(wordlist)
local firstletters = {}
for _, w in ipairs(wordlist) do
table.insert(firstletters, w:sub(1,1))
end
local graph = {}
for i, leftword in ipairs(wordlist) do
local lastletter = leftword:sub(-1)
local links = {}
for j, firstletter in ipairs(firstletters) do
if i ~= j and lastletter == firstletter then
table.insert(links, j)
end
end
table.insert(graph, links)
end
return graph
end
local function longestPath(graph)
local visited = {}
local toppath = {}
local toppathlen = 0
local stack = {}
local function recurseGraph(pos, depth)
visited[pos] = true
stack[depth] = pos
if toppathlen < depth then
toppathlen = depth
for i = 1,depth do toppath[i] = stack[i] end
end
for _, link in ipairs(graph[pos]) do
if not visited[link] then
recurseGraph(link, depth + 1)
end
end
visited[pos] = false
end
for i, _ in ipairs(graph) do
recurseGraph(i, 1)
end
return toppath
end
local function main()
local words = {}
for line in io.lines() do
words[trim(line)] = true
end
words[""] = nil
local wordlist = {}
for k, _ in pairs(words) do
table.insert(wordlist, k)
end
local graph = makeGraph(wordlist)
for _, idx in ipairs(longestPath(graph)) do
print(wordlist[idx])
end
end
main()