You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.1 KiB
49 lines
1.1 KiB
5 years ago
|
orbits = {}
|
||
|
for line in io.lines(arg[1]) do
|
||
|
a, b = line:match("(%w+)%)(%w+)")
|
||
|
if not orbits[a] then
|
||
|
orbits[a] = {}
|
||
|
end
|
||
|
table.insert(orbits[a], b)
|
||
|
end
|
||
|
|
||
|
print("Parsed...")
|
||
|
|
||
|
pos_you = nil
|
||
|
pos_san = nil
|
||
|
function getorbits(a, branches, depth)
|
||
|
local value = depth
|
||
|
if not orbits[a] then
|
||
|
return value
|
||
|
end
|
||
|
local b = branches
|
||
|
if #orbits[a] > 1 then
|
||
|
b = {table.unpack(branches)}
|
||
|
table.insert(b, {depth=depth, name=a})
|
||
|
end
|
||
|
for _, orbit in ipairs(orbits[a]) do
|
||
|
if orbit == "YOU" then
|
||
|
pos_you = {branches=branches, depth=depth}
|
||
|
end
|
||
|
if orbit == "SAN" then
|
||
|
pos_san = {branches=branches, depth=depth}
|
||
|
end
|
||
|
|
||
|
value = value + getorbits(orbit, b, depth + 1)
|
||
|
end
|
||
|
return value
|
||
|
end
|
||
|
|
||
|
print("Part 1:", getorbits("COM", {}, 0))
|
||
|
|
||
|
commbranch = 1
|
||
|
while true do
|
||
|
if pos_you.branches[commbranch] ~= pos_san.branches[commbranch] then
|
||
|
break
|
||
|
end
|
||
|
commbranch = commbranch + 1
|
||
|
end
|
||
|
branch = pos_you.branches[commbranch - 1]
|
||
|
distance = pos_you.depth + pos_san.depth - branch.depth * 2
|
||
|
print("Part 2:", distance)
|