Day 1: Part 1
This commit is contained in:
commit
66fc1893b9
44
day1/day1.lua
Normal file
44
day1/day1.lua
Normal file
@ -0,0 +1,44 @@
|
||||
--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
|
||||
|
||||
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)
|
||||
|
||||
File:close()
|
1000
day1/input.txt
Normal file
1000
day1/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user