2024-Day1-Solution.lua
· 602 B · Lua
Raw
local list1, list2 = {}, {}
for line in io.lines("input.txt") do
list1[#list1 + 1] = line:match("^(%d+)%s")
list2[#list2 + 1] = line:match("%s(%d+)$")
end
table.sort(list1)
table.sort(list2)
local counts = {}
for q = 1, #list1 do
if counts[list1[q]] == nil then counts[list1[q]] = 0 end
if counts[list2[q]] == nil then counts[list2[q]] = 0 end
counts[list2[q]] = counts[list2[q]] + 1
end
local distance, similarity = 0, 0
for q = 1, #list1 do
distance = distance + math.abs(list1[q] - list2[q])
similarity = similarity + (list1[q] * counts[list1[q]])
end
print(distance)
print(similarity)
1 | local list1, list2 = {}, {} |
2 | |
3 | for line in io.lines("input.txt") do |
4 | list1[#list1 + 1] = line:match("^(%d+)%s") |
5 | list2[#list2 + 1] = line:match("%s(%d+)$") |
6 | end |
7 | |
8 | table.sort(list1) |
9 | table.sort(list2) |
10 | |
11 | local counts = {} |
12 | for q = 1, #list1 do |
13 | if counts[list1[q]] == nil then counts[list1[q]] = 0 end |
14 | if counts[list2[q]] == nil then counts[list2[q]] = 0 end |
15 | counts[list2[q]] = counts[list2[q]] + 1 |
16 | end |
17 | |
18 | local distance, similarity = 0, 0 |
19 | for q = 1, #list1 do |
20 | distance = distance + math.abs(list1[q] - list2[q]) |
21 | similarity = similarity + (list1[q] * counts[list1[q]]) |
22 | end |
23 | |
24 | print(distance) |
25 | print(similarity) |
26 |