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

0
day06/part1.lua Normal file → Executable file
View File

0
day06/part2.lua Normal file → Executable file
View File

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)

View File

@ -17,3 +17,9 @@ function sign(n)
else return 1 else return 1
end end
end end
function foreach(t, f)
for k, v in pairs(t) do
t[k] = f(v)
end
end