2024-12-02 15:32:19 -06:00

58 lines
925 B
Lua

-- Parse Input
local file = io.open("input.text", "r")
io.input(file)
local left = {}
local right = {}
local i = 1
while true do
local line = io.read()
if line == nil then break end
local l = true
for str in string.gmatch(line, "%S+") do
if l then
left[i] = tonumber(str)
l = not l
else
right[i] = tonumber(str)
i = i + 1
end
end
end
-- Part 1
table.sort(left)
table.sort(right)
local total = 0
for i, n in ipairs(left) do
total = total + math.abs(n - right[i])
end
print("Part 1: "..total)
-- Part 2
function count(a, m)
local c = 0
for _, n in ipairs(a) do
if n == m then
c = c + 1
end
end
return c
end
total = 0
for i, n in ipairs(left) do
total = total + (n * count(right, n))
end
print("Part 2: "..total)