day 7
This commit is contained in:
parent
563e354df5
commit
602bc416d8
0
day06/part1.lua
Normal file → Executable file
0
day06/part1.lua
Normal file → Executable file
0
day06/part2.lua
Normal file → Executable file
0
day06/part2.lua
Normal file → Executable file
14
day07/part1.lua
Executable file
14
day07/part1.lua
Executable 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
28
day07/part2.lua
Executable 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)
|
Loading…
Reference in New Issue
Block a user