aoc-2024/day1/part2.lua
2024-12-01 11:12:21 -08:00

63 lines
1.3 KiB
Lua

-- see if the file exists
local function file_exists(file)
local f = io.open(file, "rb")
if f then
f:close()
end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
local function lines_from(file)
if not file_exists(file) then
return {}
end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = "input"
local lines = lines_from(file)
local left_list = {}
local right_list = {}
-- https://www.lua.org/manual/5.4/manual.html#pdf-ipairs
-- print all line numbers and their contents
for _, v in ipairs(lines) do
for n1, n2 in string.gmatch(v, "(%d+)%s+(%d+)") do
-- [](https://stackoverflow.com/a/27434198)
-- [Lua Length Operator](https://www.lua.org/manual/5.2/manual.html#3.4.6)
left_list[#left_list + 1] = n1
right_list[#right_list + 1] = n2
end
end
local right_list_count_map = {}
for _, v in ipairs(right_list) do
if right_list_count_map[v] ~= nil then
right_list_count_map[v] = right_list_count_map[v] + 1
else
right_list_count_map[v] = 1
end
end
local total = 0
for _, v in ipairs(left_list) do
local count
if right_list_count_map[v] ~= nil then
count = right_list_count_map[v]
else
count = 0
end
total = total + (v * count)
end
io.output():write(total)