This commit is contained in:
Felix Van der Jeugt 2021-12-07 08:29:45 +01:00
parent 563e354df5
commit 602bc416d8
No known key found for this signature in database
GPG key ID: 58B209295023754D
5 changed files with 48 additions and 0 deletions

14
day07/part1.lua Executable file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env luajit
require("utils")
local positions = split(io.open(arg[3]):read("*a"), ",")
foreach(positions, tonumber)
table.sort(positions)
local median = positions[#positions/2]
local cost = 0
for k, v in pairs(positions) do
cost = cost + math.abs(median - v)
end
print(cost)

28
day07/part2.lua Executable file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env luajit
require("utils")
local positions = split(io.open(arg[3]):read("*a"), ",")
foreach(positions, tonumber)
local min, max = math.huge, -math.huge
for k, v in pairs(positions) do
if v < min then min = v end
if v > max then max = v end
end
function gauss(n)
return n * (n + 1) / 2
end
local minimum = math.huge
for i = min, max do
local cost = 0
for k, v in pairs(positions) do
cost = cost + gauss(math.abs(i - v))
end
if cost < minimum then
minimum = cost
end
end
print(minimum)