From 602bc416d8ebf22d79fe21291c4ed5b0bb7066f1 Mon Sep 17 00:00:00 2001 From: Felix Van der Jeugt Date: Tue, 7 Dec 2021 08:29:45 +0100 Subject: [PATCH] day 7 --- day06/part1.lua | 0 day06/part2.lua | 0 day07/part1.lua | 14 ++++++++++++++ day07/part2.lua | 28 ++++++++++++++++++++++++++++ utils.lua | 6 ++++++ 5 files changed, 48 insertions(+) mode change 100644 => 100755 day06/part1.lua mode change 100644 => 100755 day06/part2.lua create mode 100755 day07/part1.lua create mode 100755 day07/part2.lua diff --git a/day06/part1.lua b/day06/part1.lua old mode 100644 new mode 100755 diff --git a/day06/part2.lua b/day06/part2.lua old mode 100644 new mode 100755 diff --git a/day07/part1.lua b/day07/part1.lua new file mode 100755 index 0000000..b89ca18 --- /dev/null +++ b/day07/part1.lua @@ -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) diff --git a/day07/part2.lua b/day07/part2.lua new file mode 100755 index 0000000..2931546 --- /dev/null +++ b/day07/part2.lua @@ -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) diff --git a/utils.lua b/utils.lua index 94439b9..4e32290 100644 --- a/utils.lua +++ b/utils.lua @@ -17,3 +17,9 @@ function sign(n) else return 1 end end + +function foreach(t, f) + for k, v in pairs(t) do + t[k] = f(v) + end +end