AOC-2021/02-0/main.lua
2021-12-02 18:19:33 +01:00

68 lines
1.4 KiB
Lua
Executable File

#!/usr/bin/env lua
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
function atoi_list(strings)
local ints = {}
for i,s in ipairs(strings) do
ints[#ints + 1] = tonumber(s)
end
return ints
end
function toSlices(ints)
local slices = {}
for k,i in ipairs(ints) do
if(k < (#ints - 1)) then
slices[k] = ints[k] + ints[k+1] + ints[k+2]
end
end
return slices
end
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
-------------------------------------------------
file = "input.txt"
local sums = {}
sums["up"] = 0
sums["down"] = 0
sums["forward"] = 0
allLines = lines_from(file)
for i,l in ipairs(allLines) do
local current = split(l, ' ')
local cmd = current[1]
sums[cmd] = sums[cmd] + current[2]
end
local v = sums["down"] - sums["up"]
print("vertical position: " .. v)
local result = v * sums["forward"]
io.write("The answer is ", result, ". Congrats, I hope!\n")