练习14.1
a = { {nil,nil,1,nil,nil,nil,nil},
{nil,nil,nil,nil,nil,nil,nil},
{3,nil,nil,nil,nil,nil,nil},
{nil,nil,nil,5,nil,nil,nil},
{nil,nil,nil,nil,nil,nil,nil},
{nil,nil,nil,nil,nil,7,4}
}
b = {
{nil,nil,10,nil,nil,nil,nil},
{nil,nil,nil,20,nil,nil,nil},
{nil,nil,nil,nil,nil,nil,nil},
{nil,nil,nil,50,nil,nil,nil},
{nil,nil,20,nil,nil,nil,nil},
{nil,nil,nil,10,nil,nil,4}
}
function add(a, b)
local c = {}
for i = 1, #a do
local resultline = {}
for k,va in pairs(a[i]) do
for k, vb in pairs(b[i])do
local res = (resultline[k] or 0) + va + vb
resultline[k] = (res ~= 0) and res or nil
end
end
c[i] = resultline
end
return c
end
c = add(a,b)
print(c[4][4])
练习14.2
function listnew()
return {first = 0, last = -1}
end
function pushFirst(list, value)
local first = list.first - 1
list.first = first
list[first] = value
end
function pushLast(list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function popFirst(list)
local first = list.first
if first > list.last then
print("list is empty")
return 0
end
local value = list[first]
list[first] = nil
list.first = first + 1
return value
end
function popLast(list)
local last = list.last
if list.first > last then
print("list is empty")
return 0
end
local value = list[last]
list[last] = nil
list.last = last - 1
return value
end
a = listnew()
print(popFirst(a))
练习14.3
function name2node(graph,name)
local node = graph[name]
if not node then
node = {name = name,adj = {}}
graph[name] = node
end
return node
end
function readgraph(filename)
local graph = {}
for line in io.lines(filename) do
local namefrom,nameto,Label = string.match(line,"(%S+)%s+(%S+)%s+(%d+)")
local from = name2node(graph,namefrom)
local to = name2node(graph,nameto)
temp = {[1] = true,[2] = Label}
from.adj[to] = temp
end
return graph
end
t = readgraph("test.txt")
node = name2node(t,"a")
node2 = name2node(t,"b")
print(node.adj[node2][1])