solved day 2 part 1
This commit is contained in:
parent
0dd0cd08d1
commit
3e702e29c9
67
02-0/main.lua
Executable file
67
02-0/main.lua
Executable file
@ -0,0 +1,67 @@
|
||||
#!/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")
|
Loading…
Reference in New Issue
Block a user