Skip to content

Instantly share code, notes, and snippets.

@rangercyh
Created June 6, 2022 11:19
Show Gist options
  • Save rangercyh/3a4091c0c99d61870c68c77e6159cb73 to your computer and use it in GitHub Desktop.
Save rangercyh/3a4091c0c99d61870c68c77e6159cb73 to your computer and use it in GitHub Desktop.
local e = {}
local f = {}
local function put(n, pos)
if not(f[n]) then
f[n] = pos
else
local fpos = f[n]
while e[fpos][3] do
fpos = e[fpos][3]
end
if pos - fpos > 1 then
e[fpos][3] = pos
end
end
end
function add(n1, n2, last)
if last then
n2, n1 = n1, n2
end
local pos = #e + 1
local edge = { n1, n2 }
put(n1, pos)
put(n2, pos)
table.insert(e, edge)
end
function find_all_edge(n)
local r = {}
local fpos = f[n]
local edge = e[fpos]
while true do
table.insert(r, { edge[1], edge[2] })
if edge[1] == n then
if edge[2] > n then
fpos = fpos + 1
else
fpos = edge[3]
end
elseif edge[1] < n then
fpos = edge[3]
else
break
end
edge = e[fpos]
end
return r
end
add(1, 2)
add(1, 4, true)
add(2, 3)
add(2, 5, true)
add(3, 6, true)
add(4, 5)
add(4, 7, true)
add(5, 6)
add(5, 8, true)
add(6, 9, true)
add(7, 8, true)
add(8, 9, true)
-- for k, v in ipairs(e) do
-- print(k, table.unpack(v))
-- end
for _, v in pairs(find_all_edge(5)) do
print(table.unpack(v))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment