aoc/day1/day1.lua

45 lines
931 B
Lua
Raw Normal View History

2024-12-02 13:16:38 +00:00
--Lua 5.4.2
local File = io.open("input.txt", "r")
if not File then
print("File not found")
return
end
local LeftList = {}
local RightList = {}
local Distances = {}
for Line in File:lines() do
local LeftId, RightId = Line:match("(%d+)%s+(%d+)")
table.insert(LeftList, tonumber(LeftId))
table.insert(RightList, tonumber(RightId))
end
2024-12-02 13:17:20 +00:00
File:close()
2024-12-02 13:16:38 +00:00
local function SortFunction(a, b)
return a < b
end
table.sort(LeftList, SortFunction)
table.sort(RightList, SortFunction)
if #LeftList ~= #RightList then
print("Lists are not the same size")
return
end
for ListIndex = 1, #LeftList do
local LeftId, RightId = LeftList[ListIndex], RightList[ListIndex]
local Distance = math.abs(LeftId - RightId)
Distances[ListIndex] = Distance
end
local TotalDistance = 0
for _, Distance in next, Distances do
TotalDistance = TotalDistance + Distance
end
print("Total distance:", TotalDistance)