Add Lua code for chapter 6-9 (#36)

* Add Lua code for chapter 6

* Add Lua code for chapter 7

* Add Lua code for chapter 8

* Add Lua code for chapter 9
This commit is contained in:
zhangjiongwx
2017-11-14 00:14:24 +08:00
committed by Aditya Bhargava
parent ec2890a93d
commit d0ac45bcde
6 changed files with 279 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
-- Custom deque module
require "deque"
local function person_is_seller(name)
return string.char(string.byte(name, -1)) == "m"
end
local graph = {}
graph["you"] = {"alice", "bob", "claire"}
graph["bob"] = {"anuj", "peggy"}
graph["alice"] = {"peggy"}
graph["claire"] = {"thom", "jonny"}
graph["anuj"] = {}
graph["peggy"] = {}
graph["thom"] = {}
graph["jonny"] = {}
local function search(name)
local search_queue = deque:new()
for _, value in pairs(graph[name]) do
search_queue:push_right(value)
end
-- This array is how you keep track of which people you've searched before.
local searched = {}
while search_queue:len() > 0 do
local person = search_queue:pop_left()
-- Only search this person if you haven't already searched them.
if not searched[person] then
if person_is_seller(person) then
print(person .. " is a mango seller!")
return true
else
for _, value in pairs(graph[person]) do
search_queue:push_right(value)
end
-- Marks this person as searched
searched[person] = true
end
end
end
return false
end
search("you")

View File

@@ -0,0 +1,46 @@
deque = {}
function deque:new()
self.__index = self
return setmetatable({first = 0, last = -1}, self)
end
function deque:len()
return self.last - self.first + 1
end
function deque:push_left(value)
local first = self.first - 1
self.first = first
self[first] = value
end
function deque:push_right(value)
local last = self.last + 1
self.last = last
self[last] = value
end
function deque:pop_left()
local first = self.first
if first > self.last then
error "deque is empty"
end
local value = self[first]
self[first] = nil
self.first = first + 1
return value
end
function deque:pop_right()
local last = self.last
if self.first > last then
error "deque is empty"
end
local value = self[last]
self[last] = nil
self.last = last - 1
return value
end
return deque