From 47eb33e373f0b6fe9891b786e8ba3951fc41476a Mon Sep 17 00:00:00 2001 From: Juan MarĂ­n Noguera Date: Sun, 1 Dec 2024 14:29:18 +0100 Subject: Day 01 This also includes a template to call the relevant functions from each day more conveniently. --- .gitignore | 43 ++----------------------------------------- 01.lua | 39 +++++++++++++++++++++++++++++++++++++++ main | 29 +++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 41 deletions(-) create mode 100644 01.lua create mode 100755 main diff --git a/.gitignore b/.gitignore index 6fd0a37..0a45c8d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,41 +1,2 @@ -# Compiled Lua sources -luac.out - -# luarocks build files -*.src.rock -*.zip -*.tar.gz - -# Object files -*.o -*.os -*.ko -*.obj -*.elf - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo -*.def -*.exp - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - +*~ +*.in diff --git a/01.lua b/01.lua new file mode 100644 index 0000000..fefffa4 --- /dev/null +++ b/01.lua @@ -0,0 +1,39 @@ +function lines () + local x = io.read("*n") + local y = io.read("*n") + return x, y +end + +local input = {{}, {}} + +for x, y in lines do + table.insert(input[1], x) + table.insert(input[2], y) +end + +function input:part1() + table.sort(self[1]) + table.sort(self[2]) + + local sum = 0 + for i = 1,#self[1] do + sum = sum + math.abs(self[1][i] - self[2][i]) + end + + print(sum) +end + +function input:part2() + local dict = {} + for _, val in ipairs(self[2]) do + dict[val] = (dict[val] or 0) + 1 + end + + local sum = 0 + for _, val in ipairs(self[1]) do + if dict[val] then sum = sum + val * dict[val] end + end + print(sum) +end + +return input diff --git a/main b/main new file mode 100755 index 0000000..38189ee --- /dev/null +++ b/main @@ -0,0 +1,29 @@ +#!/usr/bin/lua + +if #arg < 1 or #arg > 2 then + error ("Syntax: %s [inputfile]"):format(arg[0]) + os.exit(1) +end + +local num, letter = arg[1]:match("^(%d+)([ab])$") +if not num then + error ('Expected as first argument (e.g. "01b"), got: %s'):format(arg[1]) + os.exit(1) +end +num = tonumber(num) + +local script = ("%02d.lua"):format(num) +local infile = arg[2] or ("%02d.in"):format(num) +local input_stream = io.open(infile) +if input_stream then + io.input(input_stream) +else + print "Reading from standard input." +end + +local parsed = loadfile(script)() +if letter == 'a' then + parsed:part1() +else + parsed:part2() +end -- cgit v1.2.3