day 12
This commit is contained in:
parent
bf39b92abb
commit
1feda86093
34
day12/part1.lua
Executable file
34
day12/part1.lua
Executable file
@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env luajit
|
||||
require("utils")
|
||||
require("set")
|
||||
|
||||
local graph = {}
|
||||
local lower = set()
|
||||
for line in io.lines(arg[3]) do
|
||||
local a, b = unpack(split(line, "-"))
|
||||
local as, bs = graph[a] or {}, graph[b] or {}
|
||||
table.insert(as, b)
|
||||
table.insert(bs, a)
|
||||
if string.lower(a) == a then lower:add(a) end
|
||||
if string.lower(b) == b then lower:add(b) end
|
||||
graph[a] = as
|
||||
graph[b] = bs
|
||||
end
|
||||
|
||||
local function backtrack(i, once)
|
||||
if i == "end" then
|
||||
return 1
|
||||
else
|
||||
local paths = 0
|
||||
for k, v in pairs(graph[i]) do
|
||||
if not lower:has(v) or not once:has(v) then
|
||||
once:add(v)
|
||||
paths = paths + backtrack(v, once)
|
||||
once:remove(v)
|
||||
end
|
||||
end
|
||||
return paths
|
||||
end
|
||||
end
|
||||
|
||||
print(backtrack("start", set({"start"})))
|
36
day12/part2.lua
Executable file
36
day12/part2.lua
Executable file
@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env luajit
|
||||
require("utils")
|
||||
require("set")
|
||||
|
||||
local graph = {}
|
||||
local lower = set()
|
||||
for line in io.lines(arg[3]) do
|
||||
local a, b = unpack(split(line, "-"))
|
||||
local as, bs = graph[a] or {}, graph[b] or {}
|
||||
table.insert(as, b)
|
||||
table.insert(bs, a)
|
||||
if string.lower(a) == a then lower:add(a) end
|
||||
if string.lower(b) == b then lower:add(b) end
|
||||
graph[a] = as
|
||||
graph[b] = bs
|
||||
end
|
||||
|
||||
local function backtrack(i, once, smalls)
|
||||
if i == "end" then
|
||||
return 1
|
||||
else
|
||||
local paths = 0
|
||||
for k, v in pairs(graph[i]) do
|
||||
if not lower:has(v) or not once:has(v) then
|
||||
once:add(v)
|
||||
paths = paths + backtrack(v, once, smalls)
|
||||
once:remove(v)
|
||||
elseif smalls > 0 and v ~= "start" and v ~= "end" then
|
||||
paths = paths + backtrack(v, once, smalls - 1)
|
||||
end
|
||||
end
|
||||
return paths
|
||||
end
|
||||
end
|
||||
|
||||
print(backtrack("start", set({"start"}), 1))
|
Loading…
Reference in New Issue
Block a user