diff options
| -rw-r--r-- | .gitignore | 43 | ||||
| -rw-r--r-- | 01.lua | 39 | ||||
| -rwxr-xr-x | main | 29 |
3 files changed, 70 insertions, 41 deletions
@@ -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 @@ -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 @@ -0,0 +1,29 @@ +#!/usr/bin/lua + +if #arg < 1 or #arg > 2 then + error ("Syntax: %s <DAY><a|b> [inputfile]"):format(arg[0]) + os.exit(1) +end + +local num, letter = arg[1]:match("^(%d+)([ab])$") +if not num then + error ('Expected <DAY><a|b> 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 |
