Skip to content

Commit

Permalink
breadth-first-search more cpu- and memory efficient
Browse files Browse the repository at this point in the history
  • Loading branch information
sulai committed Aug 29, 2017
1 parent 789a859 commit 80c4618
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
17 changes: 10 additions & 7 deletions debug.lua
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,18 @@ end
-- ... do some intensive stuff ...
-- check_cpu("this took") -- log on system console
function check_cpu(msg)
if msg==nil then check_cpu_start=stat(1) return end
local percent = ((stat(1)-check_cpu_start)*100)
printh(msg.." "..flr(percent).."% of a frame")
local percent=0
if msg~=nil then
percent = ((stat(1)-check_cpu_start)*100)
printh(msg.." "..flr(percent).."% of a frame")
end
check_cpu_start=stat(1)
return percent
end

-- tests
--check_cpu()
--for i = 1, 10000 do
-- printh("consume some time")
--end
--check_cpu("for loop")
--for i = 1, 10000 do printh("consume some time") end
--check_cpu("for loop")
--for i = 1, 20000 do printh("consume more time") end
--check_cpu("second for loop")
12 changes: 3 additions & 9 deletions pathfinding.lua
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,12 @@ function find_path_breadth(x, y, limit, accept_child, accept_target)

local targets = {} -- list od coordinates {x}{y} as result of this function
local visited = {}
for x=0,47 do
visited[x] = {}
for y=0,47 do
visited[x][y]=false
end
end

local stack = {}
local read = 0
local write = 0
write=write + 1 stack[write] = {x,y} -- push
visited[x][y] = true
visited[x..","..y] = true
local dir={{x=-1,y=0},{x=1,y=0},{x=0,y=-1},{x=0,y=1} }

while write > read do
Expand All @@ -71,8 +65,8 @@ function find_path_breadth(x, y, limit, accept_child, accept_target)
-- child position
local cx = (vx+d.x)%48 -- map wrap
local cy = (vy+d.y)%48
if not visited[cx][cy] then
visited[cx][cy]=true
if not visited[cx..","..cy] then
visited[cx..","..cy]=true
if accept_child(cx,cy) then
write=write + 1 stack[write] = { cx, cy } -- push
end
Expand Down

0 comments on commit 80c4618

Please sign in to comment.