2020 day 10
This commit is contained in:
parent
c84c313362
commit
bfef11fd67
|
@ -11,3 +11,5 @@ ENV/
|
|||
# Advent of Code puzzle inputs
|
||||
input.txt
|
||||
input
|
||||
example.txt
|
||||
example
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
local adapters = {}
|
||||
|
||||
for line in io.lines() do
|
||||
table.insert(adapters, tonumber(line))
|
||||
end
|
||||
table.sort(adapters)
|
||||
|
||||
local diff_1, diff_3 = 1, 1
|
||||
|
||||
for i = 2, #adapters do
|
||||
local diff = adapters[i] - adapters[i-1]
|
||||
if diff == 1 then
|
||||
diff_1 = diff_1 + 1
|
||||
elseif diff == 3 then
|
||||
diff_3 = diff_3 + 1
|
||||
else
|
||||
print('oh no')
|
||||
return
|
||||
end
|
||||
end
|
||||
print(diff_1 * diff_3)
|
||||
|
||||
-- Maps an adapter to the list of other adapters it can connect with, to build a graph
|
||||
local accessible_adapters = {}
|
||||
|
||||
for i, adapter in ipairs(adapters) do
|
||||
accessible_adapters[adapter] = {}
|
||||
local j = i + 1
|
||||
repeat
|
||||
table.insert(accessible_adapters[adapter], adapters[j])
|
||||
j = j + 1
|
||||
until j > #adapters or adapters[j] - adapter > 3
|
||||
end
|
||||
|
||||
--[[
|
||||
For a given adapter, find how many possible paths it has.
|
||||
Uses memoization for faster output
|
||||
--]]
|
||||
local count = {}
|
||||
local function count_adapters(adapter)
|
||||
if count[adapter] then return count[adapter] end
|
||||
|
||||
count[adapter] = #accessible_adapters[adapter]
|
||||
if count[adapter] == 0 then
|
||||
count[adapter] = 1
|
||||
else
|
||||
for _, other_adapter in ipairs(accessible_adapters[adapter]) do
|
||||
count[adapter] = count[adapter] + count_adapters(other_adapter) - 1
|
||||
end
|
||||
end
|
||||
return count[adapter]
|
||||
end
|
||||
|
||||
-- Result of part 2 is the sum of paths of every adapter immediately accessible
|
||||
-- from the outlet (anything < 3).
|
||||
local total, i = 0, 1
|
||||
repeat
|
||||
total = total + count_adapters(adapters[i])
|
||||
i = i + 1
|
||||
until adapters[i] > 3
|
||||
print(total)
|
Loading…
Reference in New Issue