did day 1 in lua for fun
This commit is contained in:
parent
f7f8f632bd
commit
8b27923932
57
2024/day1/main.lua
Normal file
57
2024/day1/main.lua
Normal file
@ -0,0 +1,57 @@
|
||||
-- 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)
|
||||
Loading…
x
Reference in New Issue
Block a user