adventofcode-2021/day07/part2.lua

29 lines
513 B
Lua
Executable File

#!/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)